SWIFT:解析JSON时出现“NSURLDomain Error -1005”

时间:2015-09-29 02:24:40

标签: json swift swifty-json

我的函数getWeatherInfo()从天气Web服务检索数据,解析json,并将某些信息排序到我的数组info中。设置完我的功能后,我运行程序并收到此错误:操作无法完成。 (NSURLErrorDomain错误-1005。) 致命错误:在展开Optional值时意外发现nil。当我声明我的变量jsonResult时,它告诉我这个错误 这是代码:

var info = [AppModel]()

    func getWeatherInfo(completion: (results : NSArray?) ->Void){
        let urlPath = "http://api.openweathermap.org/data/2.5/weather?zip=92606,us&units=imperial"
        let url: NSURL = NSURL(string: urlPath)!
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
            if error != nil {
                // If there is an error in the web request, print it to the console
                println(error.localizedDescription)
            }
            var err: NSError?
            var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary // here is where I recieve my error
            if err != nil {
                // If there is an error parsing JSON, print it to the console
                println("JSON Error \(err!.localizedDescription)")
            }
            let json = JSON(jsonResult)
            var temp = json["main"]["temp"].stringValue
            var humidity = json["main"]["humidity"].stringValue
            var pressure = json["main"]["pressure"].stringValue

            var information = AppModel(temperature: temp, pressure: pressure, humidity: humidity)
            println(information)
            self.info.append(information)
            completion(results: self.info)
        })
        task.resume()


          }

    override func viewDidLoad() {
        super.viewDidLoad()
        getWeatherInfo{ (info) in
            println(info)
            }



    }

在过去之前它一直运行良好,我成功地从Web服务中获取数据并将信息排序到我的数组中。有人能指出我如何解决这个问题的正确方向吗?

1 个答案:

答案 0 :(得分:1)

偶尔的网络问题是正常的。稍等片刻再试一次。您的代码中存在错误:

        if error != nil {
            println(error.localizedDescription)
        }

应该是:

        if error != nil {
            println(error.localizedDescription)
            return
        }

如果出现错误,您必须停止,否则您也会崩溃。