squarehippo10
squarehippo10

Reputation: 1945

How to access a property list

I have created a property list with continents, countries, and random facts as shown below:

property list

I can access the top level keys from the property list easily enough:

if let path = NSBundle.mainBundle().pathForResource("countryData", ofType: "plist") {
            dict = NSDictionary(contentsOfFile: path)
        }
countries += dict!.allKeys as! [String]

If I wanted to access the second element in the vanuatu array, however, things fall apart. I would think objectForKey would get the country dictionary and then use objectForKey again to get the country array. But so far, that hasn't worked. At all...

Upvotes: 1

Views: 145

Answers (3)

Pratik Patel
Pratik Patel

Reputation: 1421

You can get data from plist file like that. I have created a plist file for countryCodes.

func fetchCounrtyCodes() -> [CountryCodes]{
let name = "name"
let dial_code = "dial_code"
let code = "code"

var countryArray = [CountryCodes]()

guard let filePath = NSBundle.mainBundle().pathForResource("CountryList", ofType: "json") else {
    print("File doesnot exist")
    return []
}
guard let jsonData = NSData(contentsOfFile: filePath) else  {
    print("error parsing data from file")
    return []
}
do {
    guard let jsonArray = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments) as? [[String:String]] else {
        print("json doesnot confirm to expected format")
        return []
    }
    countryArray = jsonArray.map({ (object) -> CountryCodes in
        return CountryCodes(name: object[name]!, dial_code:object[dial_code]!, code: object[code]!)
    })
}
catch {
    print("error\(error)")
}
return countryArray
}

struct CountryCodes{
var name = ""
var dial_code = ""
var code = ""
}

Upvotes: 1

harsh_v
harsh_v

Reputation: 3269

if let path = NSBundle.mainBundle().pathForResource("countryData", ofType: "plist") {
            dict = NSDictionary(contentsOfFile: path)

            if let australia = dict["australia"] as? [String:AnyObject]{
                // access the second element's property here
            if let vanuatu = australia["vanuatu"] as? [String]{
                // Access the vanuatu here
                } 
            }
        }

Upvotes: 3

Deepak Kumar
Deepak Kumar

Reputation: 175

if let path = NSBundle.mainBundle().pathForResource("Property List", ofType: "plist") {
       dict = NSDictionary(contentsOfFile: path)
        if let vanuatu = dict.objectForKey("australia") as? [String:AnyObject]{
            if let vanuatuArray = vanuatu["vanuatu"] as? [String]{
                print(vanuatuArray[1])
            }
        }

    }

Upvotes: 2

Related Questions