Search code examples
iosswiftnsdictionarynsdata

How to convert .plist xml string to NSDictionary


I downloaded .plist file with Swift and Alamofire and I want to read values of .plist file.

if let url = URL(string: urlString) {
    Alamofire.download(url).responseData(completionHandler: { response in
        if response.result.isSuccess {
            if let plistData = response.result.value {
                if let plistXml = String(data: data, encoding: .utf8) {
                    // plistXml contains the actual plist contents as String object.
                }

            }
        }
    })
}

I have to objects containing my downloaded .plist file:

  • plistData: the downloaded Data object
  • plistXml: String object from plistData

Using any of these objects, I want to convert the plist fie to NSDictionary or Dictionary.


Solution

  • You can use PropertyListSerialization from the Foundation framework to create a NSDictionary from the given property list data. Swift 3 Example:

    do {
        if let plist = try PropertyListSerialization.propertyList(from: plistData, format: nil)
            as? NSDictionary  {
                // Successfully read property list.
                print(plist)
    
        } else {
            print("not a dictionary")
        }
    } catch let error {
        print("not a plist:", error.localizedDescription)
    }
    

    And with

        if let plist = try PropertyListSerialization.propertyList(from: plistData, format: nil)
            as? [String: Any]  { ... }
    

    you'll get the result as a Swift Dictionary.