Search code examples
jsonswiftalamofireopenweathermap

Swift - How To Error Check JSON File?


How would I be able to check whether or not the downloaded JSON content contains an error message rather than the expected content? I've tried to validate the URL but that cannot work due to how a false subdomain (location in this case) still returns an Error Message through the JSON content. I'd appreciate it if anybody could help me out. (Note: I want to check for an invalid location entered by the user and I'm using 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()
    })
}

Solution

  • Assuming the resulting JSON has different content when there is an error, check dict for the error content. Below is an example assuming there is a key named error. Adjust as needed based on what you really get when there is an 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()
    })
    

    You should also provide a parameter to your downloadData completion handler so you can pass back an indication of success or failure so the caller can handle the result appropriately.