4

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.

pkamb
  • 33,281
  • 23
  • 160
  • 191
lawrenceli
  • 41
  • 1
  • 3
  • 1
    Are you sure that data.plist file is in your project? – Sviatoslav Yakymiv Jul 24 '14 at 15:38
  • 1
    FWIW, I had similar problem with `NSBundle.mainBundle().pathForResource`. I ended up using `NSBundle.mainBundle().resourcePath.stringByAppendingPathComponent` with my file name (with extension) as parameter. – Kreiri Jul 24 '14 at 15:41
  • @Kreiri worked like a charm, sometimes Xcode just get stupid between versions, same code worked in 7.1.1, update to 7.2 fails. my resources are in main/resources and it couldn't find them. +1 +5 if i could – μολὼν.λαβέ Dec 18 '15 at 21:00

1 Answers1

1

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
Jack Chorley
  • 2,309
  • 26
  • 28