How to access Plist file by Swift

21 views
Skip to first unread message

Eddy Wong

unread,
Oct 19, 2015, 11:55:21 AM10/19/15
to Swift Language
Any one can help me about accessing plist file in Swift 2.0

I have use below code to access an Array type of plist file and it works fine but I use the same code to open Dictionary type of plist file. It returns 'nil'. Can anyone help me or point me out what is wrong with below code. I tried to cast the NSDictionary but the return is 'nil'

 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)")

Jens Alfke

unread,
Oct 19, 2015, 12:01:02 PM10/19/15
to Eddy Wong, Swift Language

On Oct 19, 2015, at 4:27 AM, Eddy Wong <ftren...@gmail.com> wrote:

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

        

 let resultDictionary = NSDictionary(contentsOfFile: plistPathInDocument) 



plistPathInDocument isn’t a path, it’s a URL string (it starts with “file:///…” instead of “/…”.)

You can call .path on the URL instead of .absoluteString to get the filesystem path, or even better, call NSDictionary(contentsOfURL:…) directly.

—Jens
Reply all
Reply to author
Forward
0 new messages