我搜索了一种方式(或模板)如何读取存储在plist文件中的变量。我看到了一些代码,但是最新的Swift版本中没有代码可用。
我是Swift的新手,实际上我没有确切检查它的工作方式。谁能这么好,举个例子?
我有一个CollectionView,想在我的plist文件中显示字符串。那是我的plist文件:
对于每个动物键(字典类型),两个子键(名称和图片)。根->动物->动物1
所有键所使用的“名称”和“图片”均为字典。现在,我想获取字典并在收藏视图中显示名称和图片。稍后我将添加更多的变量。我希望这是可以理解的:'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) }
}