[英]How do I get content of a plist file in swift?
所以我创建了我的 plist 文件,它获取了我的 podfile 上所有 libs 许可证的列表(遵循本教程: https:https://johncodeos.com/easy-way-to-list-third-party-libraries-licenses-in-your- ios-应用程序/ )
但是现在我怎样才能得到这个文件的内容呢? 我使用的每个示例都带有一个文件路径 nil。 我究竟做错了什么?
示例代码:
let path = Bundle.path(forResource: "Acknowledgements", ofType: "plist", inDirectory: "Licenses")
我想在我的 PreferenceSpecifiers 中获取每个项目的标题和页脚文本。 我怎么能那样做?
PS.:我以前从未使用过 plist/bundle.setting 文件,所以请原谅我问了一些愚蠢的问题。 我读过,但对我来说还是阴天
您可以使用 function url(forResource:withExtension:)
而不是路径。 您可以使用此 function(将 MyPlistFile.plist 替换为您的文件名):
// Provide the key of the entry you need to read
func getStringValueFromPlist(forKey key: String) -> String {
guard let fileURL = url(forResource: "MyPlistFile.plist", withExtension: nil) else {
fatalError("Can't find \(fileName)")
}
let contents = NSDictionary(contentsOf: fileURL) as? [String: String] ?? [:]
return contents[key] ?? ""
}
要获取嵌套字典,您需要更改类型,从String
更改为字典类型,例如[String: String]
,然后在该字典中读取。
你可以试试这段代码:
let filePath = Bundle.main.path(forResource: "YourPlist", ofType: "plist")!
let plist = NSDictionary(contentsOfFile: filePath)
let value = plist?.object(forKey: "PlistKey")
首先,您应该搜索现有 plist 文件的路径,然后将其内容转换为字典,以便通过字符串键访问值。
小心强制解包( !
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.