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

How to read from a plist with Swift 3 iOS app

-免责声明-
我对 iOS 和 Swift 开发非常陌生,但我对编程并不是特别陌生。

我有一个基本的 iOS 应用程序,里面有 Swift3 个元素。
我创建了一个 plist 文件,里面有一些我想读取和显示的条目在我的申请中。 (不需要写入权限)

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

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

将不胜感激。

与您在 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] {

    }
}

注意:在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)
       }
}

这是一个 Swift 3 实现,基于 :

    /// Read Plist File.
    ///
    /// - Parameter fileURL: file URL.
    /// - Returns: return plist content.
    func ReadPlist(_ fileURL: URL) -> [String: Any]? {
        guard fileURL.pathExtension == FileExtension.plist, let data = try? Data(contentsOf: fileURL) else {
            return nil
        }
        guard let result = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: Any] else {
            return nil
        }
        print(result)
        return result
    }

对于Swift 3.0,下面的代码直接定位到key。 dict object 将提供 plist 文件中的所有内容。

if let path = Bundle.main.path(forResource: "YourPlistFile", ofType: "plist"), let dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject] {
            let value = dict["KeyInYourPlistFile"] as! String
    }

在 AppDelegate 文件中

var bundlePath:String!
    var documentPath:String!
    var plistDocumentPath:URL!
    let fileManager = FileManager()


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
    {
        bundlePath = Bundle.main.path(forResource: "Team", ofType: "plist")

        documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first

        plistDocumentPath = URL.init(string: documentPath)?.appendingPathComponent("Team.plist")
        print(plistDocumentPath.path)

        if !fileManager.fileExists(atPath: plistDocumentPath.path){

            do {
                try fileManager.copyItem(atPath: bundlePath, toPath: plistDocumentPath.path)
            } catch  {
                print("error Occured \(error.localizedDescription)")
            }

        }


        return true
    }

在ViewController

 @IBOutlet weak var TeamTable: UITableView!
    var appDelegate:AppDelegate!
    var arrayForContacts:[[String:Any]]! // array object


    override func viewDidLoad() {
        super.viewDidLoad()




        appDelegate = UIApplication.shared.delegate as! AppDelegate


    }
    override func viewWillAppear(_ animated: Bool) {

        super.viewWillAppear(animated)

        if appDelegate.fileManager.fileExists(atPath: appDelegate.plistDocumentPath.path){
            arrayForContacts = []
            if let contentOfPlist = NSArray.init(contentsOfFile: appDelegate.plistDocumentPath.path ){
                arrayForContacts = contentOfPlist as! [[String:Any]]
                TeamTable.reloadData()
            }

        }
    }

下面是如何从 Info plist 获取 BundleID 的示例:

var appBundleID = "Unknown Bundle ID"    
if let bundleDict = Bundle.main.infoDictionary, 
   let bundleID = bundleDict[kCFBundleIdentifierKey as String] as? String {
       appBundleID = bundleID
   }

同样的方式,您可以轻松访问任何密钥。这种方法适用于多目标项目。

您也可以直接从您的 plist 文件中读取值,只需

let value = Bundle.init(for: AppDelegate.self).infoDictionary?["your plist key name"] as? Any

作为Swift 4介绍Codable

第 1 步:从包中加载 Plist 文件。

步骤 2:使用 PropertyListDecoder 将 属性 列表值解码为语义 Decodable 类型。

步骤 3:创建 Codable 结构

完整代码-

 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)

    }
}

示例 Plist 文件 -> https://gist.github.com/janeshsutharios/4b0fb0e3edeff961d3e1f2829eb518db