How to read from a plist with Swift 3 iOS app

前端 未结 7 1891
無奈伤痛
無奈伤痛 2020-12-24 06:49

-Disclaimer-
I\'m extremely new to iOS and Swift development, but I\'m not particularly new to programming.

I have a basic iOS applicati

7条回答
  •  Happy的楠姐
    2020-12-24 07:05

    As Swift 4 introduces Codable

    Step 1: Load the Plist File from bundle.

    Step 2: Use PropertyListDecoder for the decoding of property list values into semantic Decodable types.

    Step 3: Create Codable Struct

    Complete code -

     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)
    
        }
    }
    

    Sample Plist file -> https://gist.github.com/janeshsutharios/4b0fb0e3edeff961d3e1f2829eb518db

提交回复
热议问题