Swift 读取本地.plist文件代码

2024-04-27  本文已影响0人  YourSummer

.....还是直接上代码
创建一个xxxx.plist文件
添加属性
你可以以 Source code打开你的xxxx.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">
    <array>
        <dict>
            <key>name</key>
            <string>张三</string>
            <key>sex</key>
            <string>男</string>
            <key>age</key>
            <integer>18</integer>
            <key>isGay</key>
            <false/>
        </dict>
        <dict>
            <key>name</key>
            <string>李四</string>
            <key>sex</key>
            <string>男</string>
            <key>age</key>
            <integer>19</integer>
            <key>isGay</key>
            <true/>
        </dict>
    </array>
</plist>

简单封装

class TestManager {

    static var testList: [[String: Any]] {
        
        guard let url = Bundle.main.url(forResource: "xxxx", withExtension: "plist") else {
            return []
        }
        
        do {
            let plistData = try NSArray(contentsOf: url, error: ())
            return plistData as? [[String: Any]] ?? []
        } catch  {
            print("NodeList = \(error.localizedDescription)")
            return []
        }
    }
}

调用:

let list = TestManager.testList
print("list =\(list)")

打印结果

list =[["name": 张三, "sex": 男, "isGay": 0, "age": 18], ["name": 李四, "age": 19, "sex": 男, "isGay": 1]]
上一篇 下一篇

猜你喜欢

热点阅读