lawrenceli
lawrenceli

Reputation: 41

`NSBundle.mainBundle().URLForResource` always returns `nil`

I am new to Swift and am using Xcode 6.

I am attempting to read data from the app's plist file, but it is not working.

The data.plist file is included in Xcode's Supporting Files group.

I am using the code below:

var dataList = NSDictionary(contentsOfURL:NSBundle.mainBundle().URLForResource("data", withExtension:"plist"))

however the NSURL:

NSBundle.mainBundle().URLForResource("data", withExtension:"plist")

always returns nil.

I don't know what is wrong.

Upvotes: 4

Views: 5354

Answers (1)

Jack Chorley
Jack Chorley

Reputation: 2344

Generally you would want to use this code to create your plist. This finds the the path to your plist and then moves it into the documents directory if it isn't already there. If you don't move it, you are not allowed to write to it, hence this chunk of code is vital. To fetch the information from the plist, use the second bit of code. Obviously if you have an array rather than a dictionary, you would have to alter it to deal with that.

var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
    path = path.stringByAppendingPathComponent("data.plist")
    let fileManager = NSFileManager.defaultManager()
    if !fileManager.fileExistsAtPath(path) {
        let sourcePath = NSBundle.mainBundle().pathForResource("data", ofType: "plist")
        fileManager.copyItemAtPath(sourcePath, toPath: path, error: nil)
}

.

let dict = NSMutableDictionary(contentsOfFile: path) as NSMutableDictionary

Upvotes: 1

Related Questions