Search code examples
iosobjective-cswift3

How to read Plist file from server and directly use it without creating local file?


I'm working on a project and I have some setting on the server which I got through the Plist file and I want to read this Plist file without creating any local copy.

Need to store this setting in the dictionary, not in the local Plist file.

any idea how can we do this?

Sample Plist like below:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>New item</key>
    <array>
        <dict>
            <key>value</key>
            <string>Data1</string>
            <key>key</key>
            <string>Tab1</string>
        </dict>
        <dict>
            <key>value</key>
            <string>Data2</string>
            <key>key</key>
            <string>Tab2</string>
        </dict>
    </array>
</dict>
</plist>

Let me know if required more detail on this.

Thanks in advance!


Solution

  • It's almost the same like loading and parsing JSON. Instead of JSONSerialization use PropertyListSerialization.

    let urlString = "http://server.com/api"
    
    let url = URL(string: urlString)
    URLSession.shared.dataTask(with:url!) { data, _, error in
      if let error = error { print(error); return } 
      do {         
          let plistDictionary = try PropertyListSerialization.propertyList(from: data!, format: nil) as! [String:Any]
          print(plistDictionary)
      } catch {
          print(error)
      }
    }.resume()