我的捆绑包中有一个plist文件,我使用以下命令将其转换为字典:
let path = Bundle.main.path(forResource: "myFile", ofType: "plist")
let dicFromFile = NSDictionary(contentsOfFile:path!)
myDictionary = dicFromFile as! [String : String]
但我也希望该应用程序检查此文件的更新,所以我把它放在共享网站上,所以它有一些网址,如下所示:
https://www.dropbox.com/s/8ri13i2wggaz6/myFile.plist
那么,如何让NSDictionary从这个文件的URL中读取?
答案 0 :(得分:1)
要从远程URL加载数据,请使用异步方式和类PropertyListSerialization
来反序列化属性列表。
let url = URL(string:"https://www.dropbox.com/s/8ri13i2wggaz6/myFile.plist"
URLSession.shared.dataTask(with:url) { (data, response, error) in
if let error = error { print(error); return }
do {
let dictionary = try PropertyListSerialization.propertyList(from: data!, format: nil) as! [String:Any]
// do something with the dictionary
} catch {
print(error)
}
}.resume()
如果属性列表文件仅包含String
值 - 如问题中所假设 - 转换为[String:String]
答案 1 :(得分:-1)
OBJ-C
NSMutableDictionary *autos = [[NSMutableDictionary alloc] initWithContentsOfURL:
[NSURL urlWithString:@"https://www.dropbox.com/s/8ri13i2wggaz6/myFile.plist"]];
迅速
let path = NSURL.init(string: "https://www.dropbox.com/s/8ri13i2wggaz6/myFile.plist")
let dicFromFile = let dicFromFile = NSDictionary.init(contentsOf: path as! URL)
myDictionary = dicFromFile as! [String : String]