NSURLErrorDomain错误代码1002描述: 无效的URL地址。

11

我是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()
           })
     })

但是我遇到了这个错误:

错误不为空::::::

操作无法完成。(NSURLErrorDomain错误-1002。)

我可以通过相同的URL在浏览器中获取JSON。 我尝试阅读这篇苹果文档,但我无法理解其描述。

这个错误代码的含义是什么?


-1002 是 NSURLErrorUnsupportedURL,这表示你的 urlPath 是错误的。 - Martin R
NSURLErrorDomain错误-1002表示NSURLErrorUnsupportedURLkCFURLErrorUnsupportedURL。最有可能的是您的URL字符串缺少URL前缀中的“http://”。 - Asif Asif
@AsifAsif:但是你从哪里获取这些错误代码的描述? - saurabh
1
@sasquatch:你可以在这里找到列表(将“Language”切换为“Obj-C”):https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/index.html#//apple_ref/doc/constant_group/URL_Loading_System_Error_Codes - Asif Asif
3个回答

29

2
除了上面的答案之外,这种情况发生的原因之一可能是,您在Info.plist中将“Allow Arbitrary Loads”设置为“false”,而您尝试加载的URL不在安全服务器上。
解决方案要么是将其设置为“true”,要么是转移到安全连接即“https://”。
希望这能帮助到某些人。祝一切顺利。

0
我遇到了同样的问题,并发现URL中缺少key参数。您需要为URL中使用的key参数设置Google地图密钥值以进行请求。如果您缺少其他键,则可能会出现此问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接