-Disclaimer-
I'm extremely new to iOS and Swift development, but I'm not particularly new to programming.
I have a basic iOS
application with Swift3
elements in it.
I've created a plist
file with some entries I want to read and display in my application. (No write access is necessary)
How can you read a value for a given key for a bundled plist
file, in Swift3?
This seems like a really simple question to me, but a bunch of searching is making me question my whole conceptual approach.
Helpful tips would be appreciated.
Same way you have done in Swift 2.3 or lower just syntax is changed.
if let path = Bundle.main.path(forResource: "fileName", ofType: "plist") {
//If your plist contain root as Array
if let array = NSArray(contentsOfFile: path) as? [[String: Any]] {
}
////If your plist contain root as Dictionary
if let dic = NSDictionary(contentsOfFile: path) as? [String: Any] {
}
}
Note: In Swift it is better to use Swift's generic type Array and Dictionary instead of NSArray
and NSDictionary
.
Edit: Instead of NSArray(contentsOfFile: path)
and NSDictionary(contentsOfFile:)
we can also use PropertyListSerialization.propertyList(from:)
to read data from plist
file.
if let fileUrl = Bundle.main.url(forResource: "fileName", withExtension: "plist"),
let data = try? Data(contentsOf: fileUrl) {
if let result = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [[String: Any]] { // [String: Any] which ever it is
print(result)
}
}