简体   繁体   中英

How can I parse this .plist file directly to the objects in Swift?

I have aa covid.plist file like below and trying to figure out how to parse to the objects and read this data ?

covid.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>key1</key>
    <string>value for key1</string>
    <key> key2</key>
    <string>valua for key1</string>
    <key>Covid1</key>
    <dict>
        <key>covid1_key</key>
        <string>covid1_value</string>
    </dict>
    <key>Covid2</key>
    <dict>
        <key>covid2_key</key>
        <string>covid2_value</string>
    </dict>
</dict>
</plist>

Your code seems to be infected so i wear mask, wash my hand and keep my mac little distance :) Anyway I think PropertyListDecoder can be used to decode plist file directly to your objects for your case

struct Covid1:Codable {
    var covid1_key:String?
    private enum CodingKeys : String, CodingKey {
              case covid2_key = "covid1_key"
    }
}

struct Covid2:Codable {
    var covid2_key:String?
    private enum CodingKeys : String, CodingKey {
              case covid2_key = "covid2_key"
    }    
}

struct PlistConfiguration:Codable {
    var key1:String?
    var covid1: Covid1?
    var covid2: Covid2?
    
    private enum CodingKeys : String, CodingKey {
              case key1 = "key1"
              case covid1 = "Covid1"
              case covid2 = "Covid2"
    }
}

And use this function for action :

func parseCovid() -> PlistConfiguration {
    let url = Bundle.main.url(forResource: "covid", withExtension: "plist")!
    let data = try! Data(contentsOf: url)
    let decoder = PropertyListDecoder()
    return try! decoder.decode(PlistConfiguration.self, from: data)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM