2

I used to read the text files from my application's bundle by using the following code. However, no matter what my application can't find them anymore. I am 100% sure that all my files are in the Assets.xcassets, I can see them, edit them, transform them from a directory to another. But my application doesn't want to read them, please tell me what I missed!!

this is the procedure I am using...

func readBundle(file:String) -> String
{
    var res: String = ""
    if let path = NSBundle.mainBundle().pathForResource(file, ofType: "txt")
    {
        let fm = NSFileManager()
        let exists = fm.fileExistsAtPath(path)
        if(exists)
        {
            let c = fm.contentsAtPath(path)
            res = NSString(data: c!, encoding: NSUTF8StringEncoding) as! String
        }
    }
    return res
}

I am using it like this:

let res = readBundle("test")
print(res)
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Sahli Simo
  • 85
  • 2
  • 7
  • I'm not sure that storing those text files as Assets is the way to go. I'd stick with @Pyro''s answer for all kinds of bundle resources that are not artwork. – Lasse Apr 12 '16 at 19:27
  • http://stackoverflow.com/a/30808846/2303865 – Leo Dabus Apr 12 '16 at 20:17
  • http://stackoverflow.com/questions/34548771/swift-how-do-i-get-the-file-path-inside-a-folder/34548888?s=2|1.1752#34548888 – Leo Dabus Apr 12 '16 at 20:18

2 Answers2

4

when storing non image files in XCAssets, you should use NSDataAsset to acccess their content

https://developer.apple.com/library/ios/documentation/UIKit/Reference/NSDataAsset_Class/

func readBundle(file:String) -> String
{
    var res = ""
    if let asset = NSDataAsset(name: file) ,
        string = String(data:asset.data, encoding: NSUTF8StringEncoding){
        res = string
    }
    return res
}
Pierre Oleo
  • 1,209
  • 1
  • 8
  • 6
3

In the another option then 'XCAssets' you can create a separate folder/group of your resources other than images in the project structure, check if they exist in the Copy Bundle Resource in the Build phases section of your project's main target

If you add resource like this your current code should work as it is

func readBundle(file:String) -> String
{
    var res: String = ""
    if let path = NSBundle.mainBundle().pathForResource(file, ofType: "txt")
    {
       //you should be able to get the path
       //other code as you has written in the question
    }
    return res
}
HardikDG
  • 5,892
  • 2
  • 26
  • 55