如何在 swift 中获取 plist 文件的内容?

How do I get content of a plist file in swift?

所以我创建了 plist 文件,它获取了我的 podfile 中所有 libs 许可证的列表(遵循本教程:https://johncodeos.com/easy-way-to-list-third-party-libraries-licenses-in-your-ios-app/

但是现在我怎样才能得到这个文件的内容呢?我使用的每个示例都带有一个文件路径 nil。我做错了什么?

示例代码:

let path = Bundle.path(forResource: "Acknowledgements", ofType: "plist", inDirectory: "Licenses")

我的plist文件结构:

我想获取 PreferenceSpecifiers 中每个项目的标题和页脚文本。我该怎么做?

PS.: 我以前从未使用过 plist/bundle.setting 文件,所以请原谅我问了一些愚蠢的问题。我读过,但 it/s 对我来说仍然是阴天

您可以使用函数 url(forResource:withExtension:) 而不是路径。您可以使用此功能(将 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 文件的路径,然后将其内容转换为字典,以便通过字符串键访问值。

小心强制解包(!)