json - Swift - 如何错误检查 JSON 文件?

标签 json swift alamofire openweathermap

如何检查下载的 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 具有不同的内容,请检查 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 完成处理程序提供一个参数,以便您可以传回成功或失败的指示,以便调用者可以适本地处理结果。

关于json - Swift - 如何错误检查 JSON 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41582315/

相关文章:

swift - 从非 tableview 类更改自定义 UITableViewCell 标签会导致错误

ios - 尝试使用 Swiftyjson 解析 json 文件

python - Django 和 postgres - 在模型字段中将数据存储为 json 的缺点

json - 为什么 int-http 的 JSON 负载是 :outbound-gateway give 400 Bad Request?

ios - 隐藏状态栏但封面仍然拦截触摸

python - Alamofire 将 PNG 上传到具有白色背景的 Flask

ios - AlamofireObjectMapper 无法推断通用参数 'T'

javascript - 从 javascript 按时间间隔调用 C# 方法

java - 在 Eclipse 控制台中没有输出的 Apache 500 错误

swift - PromiseKit firSTLyOn 样式方法