Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xcode/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
获取JSON数据函数-地址noch可访问-NSURErrorDomain错误-1002_Json_Xcode_Swift - Fatal编程技术网

获取JSON数据函数-地址noch可访问-NSURErrorDomain错误-1002

获取JSON数据函数-地址noch可访问-NSURErrorDomain错误-1002,json,xcode,swift,Json,Xcode,Swift,我有一个从某个ip地址检索JSON数据的函数。 如果无法访问ip,xcode会在 var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary 无法完成该操作。NSURlerorDomain错误-1002。致命错误:在展开可选值时意外发现nil 如何检查jsonResul

我有一个从某个ip地址检索JSON数据的函数。 如果无法访问ip,xcode会在

var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
无法完成该操作。NSURlerorDomain错误-1002。致命错误:在展开可选值时意外发现nil

如何检查jsonResult是否有效或ip地址是否有效

func getJsonData() {

        let urlAsString = NSUserDefaults.standardUserDefaults().objectForKey("ipAddress") as String
        let url: NSURL  = NSURL(string: urlAsString)!
        let urlSession = NSURLSession.sharedSession()

        let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
            if (error != nil) {
                println(error.localizedDescription)
            }
            var err: NSError?

            var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary


            if (err != nil) {
                println("JSON Error \(err!.localizedDescription)")
            }

            //Display Data
            dispatch_async(dispatch_get_main_queue(), {
                self.label.text = String(format: "%.3f", (jsonResult["pwr"] as Float!)/1000)
            })
        })
        jsonQuery.resume()
    }

谢谢

创建一个如下所示的方法来检查有效的url

func validateUrl (stringURL : NSString) -> Bool {

    var urlRegEx = "((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))+"
    let predicate = NSPredicate(format:"SELF MATCHES %@", argumentArray:[urlRegEx])
    var urlTest = NSPredicate.predicateWithSubstitutionVariables(predicate)

    return predicate.evaluateWithObject(stringURL)
}
然后更新您的方法。添加一行以调用validate url方法

func getJsonData() {

    let urlAsString = NSUserDefaults.standardUserDefaults().objectForKey("ipAddress") as String

    var isValidURL = validateUrl(urlAsString)
    if (!isValidURL) {
        // Return from here. URL is invalid
        return
    }

    let url: NSURL  = NSURL(string: urlAsString)!
    let urlSession = NSURLSession.sharedSession()

    let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
        if (error != nil) {
            println(error.localizedDescription)
        }
        var err: NSError?

        var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary


        if (err != nil) {
            println("JSON Error \(err!.localizedDescription)")
        }

        //Display Data
        dispatch_async(dispatch_get_main_queue(), {
            self.label.text = String(format: "%.3f", (jsonResult["pwr"] as Float!)/1000)
        })
    })
    jsonQuery.resume()
}
仅将错误打印到调试器控制台是不够的。必须处理错误。问问自己——如果没有互联网连接,你想做什么?是否要向用户显示错误?是否再次尝试发送请求

基本事实是,如果出现错误,您将无法继续并解析数据。数据不存在,未加载。如果您试图解析为零的数据,您的应用程序将崩溃

if (error != nil) {
    //XXX: display error to the user, e.g. using an alert
    return; //return immediately, don't proceed to parsing.
}

我不认为URL的有效性是这里的问题。这是关于失去互联网连接。
if (error != nil) {
    //XXX: display error to the user, e.g. using an alert
    return; //return immediately, don't proceed to parsing.
}