Search code examples
iosswiftxcodeswift3alamofire

Save Alamofire Result as Variable?


I've been trying to find out how to save a part of a JSON response from Alamofire as a variable to make an if statement and can't seem to find how to do it.

I made a piece of code to use as an example for the question which consists of the following:

import UIKit
import Alamofire

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()


        Alamofire.request("http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44143256ee15e9c3f521ca062463dd8d").responseJSON { response in
            print(response.result)   // result of response serialization

            if let JSON = response.result.value {
                print("JSON: \(JSON)")
            }
        }  
    } 
}

I get the following response from the API request:

JSON: {
base = stations;
clouds =     {
    all = 0;
};
cod = 200;
coord =     {
    lat = "51.51";
    lon = "-0.13";
};
dt = 1485031800;
id = 2643743;
main =     {
    humidity = 83;
    pressure = 1026;
    temp = "270.54";
    "temp_max" = "273.15";
    "temp_min" = "267.15";
};
name = London;
sys =     {
    country = GB;
    id = 5091;
    message = "0.0038";
    sunrise = 1484985141;
    sunset = 1485016345;
    type = 1;
};
visibility = 7000;
weather =     (
            {
        description = haze;
        icon = 50n;
        id = 721;
        main = Haze;
    }
);
wind =     {
    speed = 1;
};
}

From this JSON response I would like to save the weather description so I could use the following statement:

if var currentWeather = sunny {
     return "Nice day!"
} else {
     return "Uh-Oh, keep warm!"
}

If anyone could help me with this I would greatly appreciate it! If I have to use SwiftyJSON to make it easier that's fine I've just been struggling with this for a while and need to figure it out!


Solution

  • You can parse your result following the printout of your JSON response:

    guard let JSON = response.result.value as? [String:Any],
        let weather = JSON["weather"] as? [[String:Any]] else {
        print("Could not parse weather values")
        return
    }
    
    for element in weather {
        if let description = element["description"] as? String {
            print(description)
        }
    }
    

    If you wanted to save the result, or do something based on a certain result as you described, you could insert something else instead of just print(description) like:

    if description == "sunny" {
        //do something
    }
    

    Let me know if this makes sense. Keep in mind that ( and ) in the Xcode console means "Array".