【问题标题】:Swift - How To Error Check JSON File?Swift - 如何错误检查 JSON 文件?
【发布时间】:2017-01-11 03:42:29
【问题描述】:

如何检查下载的 JSON 内容是否包含错误消息而不是预期内容?我已尝试验证 URL,但由于错误的子域(在本例中为位置)仍然通过 JSON 内容返回错误消息,因此无法验证。如果有人可以帮助我,我将不胜感激。 (注意:我想检查用户输入的位置是否无效,并且我正在使用 OpenWeatherMap API。)

func downloadData(completed: @escaping ()-> ()) {
    print(url)

    //UIApplication.shared.openURL(url as URL)
    Alamofire.request(url).responseJSON(completionHandler: {
        response in
        let result = response.result

        if let dict = result.value as? JSONStandard, let main = dict["main"] as? JSONStandard, let temp = main["temp"] as? Double, let weatherArray = dict["weather"] as? [JSONStandard], let weather = weatherArray[0]["main"] as? String, let name = dict["name"] as? String, let sys = dict["sys"] as? JSONStandard, let country = sys["country"] as? String, let dt = dict["dt"] as? Double {

            self._temp = String(format: "%.0f °F", (1.8*(temp-273))+32)
            self._weather = weather
            self._location = "\(name), \(country)"
            self._date = dt
        }

        completed()
    })
}

【问题讨论】:

    标签: json swift alamofire openweathermap


    【解决方案1】:

    假设发生错误时生成的 JSON 内容不同,请检查 dict 以获取错误内容。下面是一个假设有一个名为error 的键的示例。出现错误时,根据实际得到的情况进行调整。

    Alamofire.request(url).responseJSON(completionHandler: {
        response in
        let result = response.result
    
        if let dict = result.value as? JSONStandard {
            if let error = dict["error"] {
                // parse the error details from the JSON and do what you want
            } else if let main = dict["main"] as? JSONStandard, let temp = main["temp"] as? Double, let weatherArray = dict["weather"] as? [JSONStandard], let weather = weatherArray[0]["main"] as? String, let name = dict["name"] as? String, let sys = dict["sys"] as? JSONStandard, let country = sys["country"] as? String, let dt = dict["dt"] as? Double {
                self._temp = String(format: "%.0f °F", (1.8*(temp-273))+32)
                self._weather = weather
                self._location = "\(name), \(country)"
                self._date = dt
            } else {
                // Unexpected content, handle as needed
            }
        }
    
        completed()
    })
    

    您还应该为您的 downloadData 完成处理程序提供一个参数,以便您可以传回成功或失败的指示,以便调用者可以适当地处理结果。

    【讨论】:

      猜你喜欢
      • 2015-06-05
      • 2018-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多