我是 iOS 开发新手。我正在尝试加载 JSON,这是我的功能:
func loadmyJSON (urlPath: String) {
let url: NSURL = NSURL(string: urlPath)!
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
println("Task completed")
if(error != nil) {
// If there is an error in the web request, print it to the console
println("error not nil::::::")
println(error.localizedDescription)
}
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
if(err != nil) {
// If there is an error parsing JSON, print it to the console
println("JSON Error \(err!.localizedDescription)")
}
let results: NSArray = jsonResult["variants"] as NSArray
dispatch_async(dispatch_get_main_queue(), {
self.jsonTable = results
self.productView!.reloadData()
})
})
但我收到此错误:
error not nil::::::
The operation couldn’t be completed. (NSURLErrorDomain error -1002.)
我可以通过相同的 URL 在浏览器中获取 JSON。 我尝试阅读this Apple Doc,但无法获取描述。
这个错误代码是什么意思?
NSURLErrorDomain error -1002
表示 NSURLErrorUnsupportedURL
或 kCFURLErrorUnsupportedURL
。这表明提供了错误的 URL,在大多数情况下,URL 前缀中缺少 http://
。
所有
NSURLErrorDomain
代码的列表可以在这里找到:https://developer.apple.com/documentation/foundation/1508628-url_loading_system_error_codes
除了上述答案之外,发生这种情况的原因之一是,
您可能已在 Info.plist 中将 Allow Arbitrary Loads 设置为
false
,并且您尝试加载的 URL 不在安全服务器上。
解决此问题的方法是将其设置为
true
,或者移至安全连接,即 https://
。
希望它对某人有帮助。祝一切顺利。
我遇到了同样的问题,发现 URL 中缺少 key 参数。您需要为用于发出请求的 URL 中的关键参数设置 Google 地图键 值。如果您缺少其他钥匙,也可能会发生这种情况。