How can I access a dictionary plist in swift?

I have used below code to access a plist file. If the plist is array type of plist, it works fine. But if the plist is dictionary type, the return value is always nil. Even I tried to cast to Dictionary, the result still nil. Anyone can help to point me what is the problem in below code?


var plistPathInDocument:String = String()

let rootPath = NSSearchPathForDirectoriesInDomains(.DocumentationDirectory, .UserDomainMask, true)[0]

let url = NSURL(string: rootPath)

plistPathInDocument = (url?.URLByAppendingPathExtension("TestList.plist").absoluteString)!

let resultDictionary = NSDictionary(contentsOfFile: plistPathInDocument)

print("\(resultDictionary)")

I’m not sure what’s going on with your code. You seem to be mixing up file URLs, paths, strings and so on. For example, if you have path string you can’t create a file URL by calling:

let url = NSURL(string: rootPath)

you have to use:

let url = NSURL(fileURLWithPath: rootPath)

Likewise, you can’t get a path from a file URL using

absoluteString
; if it’s a valid file URL then
path
should do.

Also,

-URLByAppendingPathExtension:
is for adding extensions (like
.txt
) not for adding path components. You want
-URLByAppendingPathComponent:
instead.

Finally, my general advice is, choose a file representation scheme and stick with it. For example, once you’ve decided to use file URLs, use them everywhere and treat paths as an import/export format.

In this case, you don’t even need to do that, because all the APIs you need to use deal with file URLs. As such, you can rewrite your code as:

let docDirURL = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
let fileURL = docDirURL.URLByAppendingPathComponent("TestList.plist")
let dict = NSDictionary(contentsOfURL: fileURL)
NSLog("%@", dict ?? "nil")

Share and Enjoy

Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
How can I access a dictionary plist in swift?
 
 
Q