如何使用Swift 3 iOS应用程序阅读plist

Jam*_*ell 29 xcode plist ios swift swift3

-Disclaimer-
我是iOS和Swift开发的新手,但我对编程并不陌生.

我有一个基本的iOS应用程序,其中包含Swift3元素.
我创建了一个plist文件,其中包含一些我想要阅读并在我的应用程序中显示的条目.(无需写入权限)

如何plist在Swift3中读取捆绑文件的给定键的值?

这对我来说似乎是一个非常简单的问题,但是一堆搜索让我质疑我的整个概念方法.

有用的提示将不胜感激.

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而不是NSArrayNSDictionary.

编辑:而不是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)

  • @Doc值得注意的是,有些plist是预先定义的.最值得注意的是,info.plist:```static let BASE_URL = Bundle.main.infoDictionary!["MY_BASE_URL"] as!String``` (9认同)
  • 为了强调@Dilapidus非常好的观点,这个问题的正确/接受答案应该基于`Bundle.main.infoDictionary` ......它就在那里等着你.无需更多代码. (2认同)

Jac*_*ack 9

正如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