Nir*_*v D 70
你在Swift 2.3或更低版本中完成的方式只是改变了语法.
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] {
}
}
Run Code Online (Sandbox Code Playgroud)
注意:在Swift中,最好使用Swift的泛型类型Array和Dictionary而不是NSArray和NSDictionary.
编辑:而不是NSArray(contentsOfFile: path)和NSDictionary(contentsOfFile:)我们也可以利用PropertyListSerialization.propertyList(from:)从读取数据plist文件.
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)
}
}
Run Code Online (Sandbox Code Playgroud)
正如Swift 4引入了Codable
第1步:从包中加载Plist文件.
步骤2:使用PropertyListDecoder将属性列表值解码为语义Decodable类型.
第3步:创建可编码结构
完整代码 -
func setData() {
// location of plist file
if let settingsURL = Bundle.main.path(forResource: "JsonPlist", ofType: "plist") {
do {
var settings: MySettings?
let data = try Data(contentsOf: URL(fileURLWithPath: settingsURL))
let decoder = PropertyListDecoder()
settings = try decoder.decode(MySettings.self, from: data)
print("toolString is \(settings?.toolString ?? "")")
print("DeviceDictionary is \(settings?.deviceDictionary?.phone ?? "")")
print("RootPartArray is \(settings?.RootPartArray ?? [""])")
} catch {
print(error)
}
}
}
}
struct MySettings: Codable {
var toolString: String?
var deviceDictionary: DeviceDictionary?
var RootPartArray: [String]?
private enum CodingKeys: String, CodingKey {
case toolString = "ToolString"
case deviceDictionary = "DeviceDictionary"
case RootPartArray
}
struct DeviceDictionary: Codable {
var phone: String?
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
phone = try values.decodeIfPresent(String.self, forKey: .phone)
}
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
toolString = try values.decodeIfPresent(String.self, forKey: .toolString)
deviceDictionary = try values.decodeIfPresent(DeviceDictionary.self, forKey: .deviceDictionary)
RootPartArray = try values.decodeIfPresent([String].self, forKey: .RootPartArray)
}
}
Run Code Online (Sandbox Code Playgroud)
示例Plist文件 - > https://gist.github.com/janeshsutharios/4b0fb0e3edeff961d3e1f2829eb518db
| 归档时间: |
|
| 查看次数: |
34689 次 |
| 最近记录: |