Search code examples
iosjsonswiftalamofire

Downloading and parsing json in Swift with Alamofire


Sorry I am quite new to this and they're may be something glaringly obvious that is going over my head but I am getting the following error message with this code:

"fatal error: unexpectedly found nil while unwrapping an Optional value."

   var jsonReceived = Alamofire.request(.GET, getJsonURL).responseJSON {
        (request, response, jsonData, error) in
        if jsonData == nil {
            println(error)
        } else {
            println(jsonData)
            var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
            println(jsonResult)
        }
    }

Solution

  • Just for simplicity, I've put the Alamofire.request code into the viewDidLoad(). You could put it wherever you want.

    override func viewDidLoad() {
        Alamofire.request(.GET, getJsonURL).responseJSON {
                (request, response, jsonData, error) in
                if error != nil {
                    println(error)
                } else if let json = jsonData as? [String:AnyObject] {
                    println(json)
    
                    // call a function with the new data. 
                    self.processNewData(json)
    
                    // or you could just use the json object here
                    if let str = json["foo"] as? String {
                        self.myButton.setTitle(str, forState: .Normal)
                    }
                } else {
                    println("Failed to cast JSON to [String:AnyObject]")
                }
            }
    }
    
    func processNewData(json: [String:AnyObject]){
        // do whatever you want here with the parsed JSON
        if let str = json["bar"] as? String {
            myLabel.text = str
        }
    }