Property lists are key part of organizing data in an app. Learn how to update your app’s data whenever you want by storing the Property List on a server, and loading the data at runtime. We’ll look at two methods of retrieving the Property List file from your server. The second is obviously a bit more code, but has some benefits.
Example 1
func getServerPropertyList() {
guard let url = URL(string: "https://ENTERYOURDOMAIN.com/Properties.plist" ) else {
print ("not connected to the internet or some other issue")
return
}
if let dict = NSDictionary(contentsOf: url) as? [String : Any] {
print(dict)
for (key, value) in dict {
//iterate through the dictionary
}
}
}
Example 2
//declare this var in your class…
var entireDict = [String : Any]()
func getServerPropertyListAlternate () {
let url = URL(string: "https://ENTERYOURDOMAIN.com/Properties.plist" )
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil {
print("didn’t work, (String(describing: error))")
DispatchQueue.main.asyncAfter(deadline: .now() ) {
//do anything that affects the UI here,
// but setting variables is okay outside of this
self.unsuccessfulParse()
}
} else {
do {
let data = try Data(contentsOf:url!)
self.entireDict = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as! [String : Any]
DispatchQueue.main.asyncAfter(deadline: .now()) {
print(self.entireDict )
}
} catch let error as NSError {
print(error)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { // in half a second…
//do anything that affects the UI here,
// but setting variables is okay outside of this
self.unsuccessfulParse()
}
}
}
}.resume()
}
func unsuccessfulParse () {
if ( entireDict.count > 0 ){
//reuse existing entireDict data
} else {
if let path = Bundle.main.path(forResource: "Properties", ofType:"plist"), let dict = NSDictionary(contentsOfFile: path) as? [String: Any] {
entireDict = dict
print(entireDict )
//use the data
//populate your GUI
}
}
}