Kate
Kate

Reputation: 1247

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

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.

Upvotes: 0

Views: 913

Answers (2)

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

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:

enter image description here

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!

enter image description here

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.

enter image description here

Here is my plist format for more information:

enter image description here

Reference from here Hope this will help you.

Upvotes: 1

Kate
Kate

Reputation: 1247

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

Upvotes: 0

Related Questions