我这里有一段代码:
let endpointURL = URL(string: "http://foobar.com")
let downloadTask = URLSession.shared.downloadTask(with: endpointURL!, completionHandler: { url, response, error in
if (error == nil) {
let dataObject = NSData(contentsOfURL: endpointURL!)
let jsonArray: Array = JSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as Array
}
})
downloadTask.resume()
我有个问题:
Ambiguous use of 'init(contentsOfURL:)' for NSData part
我怎样才能使它明确?
最佳答案
我建议在Swift 3中使用类似的方法,加载JSON数据dataTask
比downloadTask
更合适。
let endpointURL = URL(string: "http://foobar.com")
let dataTask = URLSession.shared.dataTask(with: endpointURL!) { data, response, error in
guard error == nil else {
print(error!)
return
}
do {
// the assumed result type is `[[String:Any]]` cast it to the expected type
if let jsonArray = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]] {
print(jsonArray)
}
} catch {
print(error)
}
}
dataTask.resume()
关于ios - 在ContentsOfUrl中使用数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46080809/