Swift 5:如何读取plist文件中的变量?

Swift 5: How to read variables in plist files?

我搜索了一种方法(或模板)来读取存储在 plist 文件中的变量。 我看到了一些代码,但没有代码适用于最新的 Swift 版本。

我是 Swift 的新手,实际上我并没有确切地检查它是如何工作的.. 谁能这么好给我举个例子吗?

我有一个 CollectionView 并想显示我的 plist 文件中的字符串。 那是我的 plist 文件:

对于每个动物键(字典类型)两个子键(名称和图片)。 根 --> 动物 --> Animals1

所有 "name" 和 "picture" 键都是字典。 现在我想获取字典并在 collection 视图中显示名称和图片。稍后我将添加更多变量。我希望它是可以理解的:'D

我的代码不完整:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    let path = Bundle.main.path(forResource: "Animals", ofType:"plist")!
    let dict = NSDictionary(contentsOfFile: path)
    SortData = dict!.object(forKey: "Animals") as! [Dictionary]
}

您可以像之前那样使用 PropertyListSerialization 或 NSDictionary。这里很可能是由于其他原因你弄错了。

class ViewController: UIViewController {

    var animals = [String: Any]()

    override func viewDidLoad() {
        super.viewDidLoad()

        fetchAnimals() // or fetchPropertyListAnimals()
        fetchPropertyListAnimals()
    }

    func fetchAnimals() {

        guard let path = Bundle.main.path(forResource: "Animals", ofType: "plist") else {
            print("Path not found")
            return
        }

        guard let dictionary = NSDictionary(contentsOfFile: path) else {
            print("Unable to get dictionary from path")
            return
        }

        if let animals = dictionary.object(forKey: "Animals") as? [String: Any] {
            self.animals = animals
        } else {
            print("Unable to find value for key named Animals")
        }
    }

    func fetchPropertyListAnimals() {
        var propertyListFormat =  PropertyListSerialization.PropertyListFormat.xml
        guard let path = Bundle.main.path(forResource: "Animals", ofType: "plist") else {
            print("Path not found")
            return
        }
        guard let data = FileManager.default.contents(atPath: path) else {
            print("Unable to get data from path")
            return
        }
        do {
            if let animals = try PropertyListSerialization.propertyList(from: data, options: .mutableContainersAndLeaves, format: &propertyListFormat) as? [String: Any] {
                self.animals = animals
            } else {
                print("Unable to find value for key named Animals")
            }

        } catch {
            print("Error reading plist: \(error), format: \(propertyListFormat)")
        }
    }
}

您的 属性 列表格式不是很方便。因为你想要一个数组,所以创建 属性 列表,其中包含键 animals 的数组(并将所有键命名为小写)

<?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>animals</key>
    <array>
        <dict>
            <key>name</key>
            <string>Tiger</string>
            <key>picture</key>
            <string>tiger_running</string>
        </dict>
        <dict>
            <key>name</key>
            <string>Jaguar</string>
            <key>picture</key>
            <string>jaguar_sleeping</string>
        </dict>
    </array>
</dict>
</plist>

然后创建两个结构体

struct Root : Decodable {
    let animals : [Animal]
}

struct Animal : Decodable {
    let name, picture : String
}

和数据源数组

var animals = [Animal]()

并解码内容

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    let url = Bundle.main.url(forResource: "Animals", withExtension:"plist")!
    do {
        let data = try Data(contentsOf: url)
        let result = try PropertyListDecoder().decode(Root.self, from: data)
        self.animals = result.animals
    } catch { print(error) }
}

PropertyListDecoderPropertyListSerialization 是 Swift 中最先进的。 NSDictionary/NSArray API 是 objective-c-ish 并且已过时。