Sahli Simo
Sahli Simo

Reputation: 87

I cant read my text files from my application's Bundle

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)

Upvotes: 2

Views: 1980

Answers (2)

HardikDG
HardikDG

Reputation: 6112

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
}

Upvotes: 3

Pierre Oleo
Pierre Oleo

Reputation: 1209

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
}

Upvotes: 4

Related Questions