swift: could not read (local) plist file to Dictionary in a playground

馋奶兔 提交于 2020-01-03 04:46:29

问题


1.I creat a new playground,and add my 2.plist to the playground's package content folder. 2.I tried:

var myDict: NSDictionary?
if let path = NSBundle.mainBundle().pathForResource("2", ofType:"plist"){
println(path)// "/var/folders/....../2.plist"

myDict = NSDictionary(contentsOfFile: path) as? Dictionary<String, AnyObject>
println(myDict)// nil

let url:NSURL! = NSBundle.mainBundle().URLForResource("2", withExtension:"plist")
myDict = NSDictionary(contentsOfURL: url)
println(myDict) //nil

var str = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)! 
// ??? here display the String content of 2.plist
} else {
println("exist")
}

3.I have tried many ways, but could not read the plist to dictionary.Why???

Many thanks for you help.


回答1:


I think you are adding your Plist file wrongly so follow this step:

File Inspector

In the XCode menu just select View -> Utilities -> Show File Inspector:

You’ll see a panel on the right hand side. The Playground Settings section will have your path to the Resource folder. Just click the little arrow, and open up the Resource folder!

Now just add your plist file in the Resources folder, and code away!

Here you can see you code is working perfectly after following this steps.

Here is my plist format for more information:

Reference from here Hope this will help you.




回答2:


There are some thing wrong with the 2.plist. The content of 2.plist could not be read with NSDictionary,but with NSArray.



来源:https://stackoverflow.com/questions/28956211/swift-could-not-read-local-plist-file-to-dictionary-in-a-playground

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!