如何将 .plist xml 字符串转换为 NSDictionary

How to convert .plist xml string to NSDictionary

我用 SwiftAlamofire 下载了 .plist 文件,我想读取 .plist 文件的值。

if let url = URL(string: urlString) {
    Alamofire.download(url).responseData(completionHandler: { response in
        if response.result.isSuccess {
            if let plistData = response.result.value {
                if let plistXml = String(data: data, encoding: .utf8) {
                    // plistXml contains the actual plist contents as String object.
                }

            }
        }
    })
}

我必须包含我下载的 .plist 文件的对象:

使用这些对象中的任何一个,我想将 plist fie 转换为 NSDictionary 或 Dictionary。

  1. 使用SWXMLHash
  2. 阅读 plistXml 并使用该文档逐步解析xml。
  3. 将您想要放入 plistXml 中的元素保存到字典中

祝你好运!

您可以使用 Foundation 框架中的 PropertyListSerialization 创建一个 NSDictionary 来自给定的 属性 列表数据。 Swift 3 示例:

do {
    if let plist = try PropertyListSerialization.propertyList(from: plistData, format: nil)
        as? NSDictionary  {
            // Successfully read property list.
            print(plist)

    } else {
        print("not a dictionary")
    }
} catch let error {
    print("not a plist:", error.localizedDescription)
}

并与

    if let plist = try PropertyListSerialization.propertyList(from: plistData, format: nil)
        as? [String: Any]  { ... }

您将得到 Swift Dictionary 的结果。

这里是 objective-C 版本的代码。你可以很容易地转换它。

NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];
    NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"register.plist"];

    if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
        plistPath = [[NSBundle mainBundle] pathForResource:@"register" ofType:@"plist"];
    }

    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistPath];