【发布时间】:2018-10-06 16:13:53
【问题描述】:
我正在使用 Swift 创建一个应用程序,我必须使用以下 URL 显示国家列表:
在这里我只需要获取name 密钥并添加到我的NSMutableArray。当我尝试使用 URLSession 解析它时,出现错误:
expression produced error: error: /var/folders/_3/27lhgzw9699c4_yg37r72_d80000gp/T/expr40-bcf47d..swift:1:65: error: use of undeclared type 'Foundation'
Swift._DebuggerSupport.stringForPrintObject(Swift.UnsafePointer<Foundation.Data>(bitPattern: 0x105c0c2f0)!.pointee)
下面是我的代码:
func fetchCountryList(countryURL:URL, completion:@escaping (NSDictionary) -> ()) {
print(countryURL)
let request = NSMutableURLRequest( url: countryURL as URL)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
do{
if let data = data,
let jsonString = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
, error == nil {
completion(jsonString)
} else {
print("error=\(error!.localizedDescription)")
let errorDict = ["error_status":true,"message":error!.localizedDescription] as [String : Any]
completion(errorDict as NSDictionary)
}
}
catch{
print("error=\(error.localizedDescription)")
let errorDict = ["error_status":true,"message":error.localizedDescription] as [String : Any]
completion(errorDict as NSDictionary)
}
}
task.resume()
}
任何人都可以在这里建议我我的错误。提前致谢!
【问题讨论】:
-
不要在 Swift 中使用
NSDictionary。使用正确的 Swift 字典。不要在 Swift 中使用NSMutableURLRequest。使用URLRequest。不要在 Swift 中使用.mutableContainers选项(一旦切换到 Swift 字典)。
标签: ios json swift parsing jsonparser