How to get the result value of Alamofire.request().responseJSON in swift 2?

If you don't mind using SwiftyJSON library, here's a working example in Xcode 7 Beta 5 + Alamofire 2.0.0-beta.1 + SwiftyJSON (xcode7 branch)

Alamofire.request(.GET, url, parameters: params, encoding: ParameterEncoding.URL).responseJSON { (_, _, result) in
    switch result {
        case .Success(let data):
            let json = JSON(data)
            let name = json["name"].string
        case .Failure(_, let error):
            print("Request failed with error: \(error)")
    }
}

Edit:

Updated SwiftyJSON git page


The accepted answer works great but with the introduction of Alamofire 3.0.0 there are some breaking changes that affects this implementation.
The migration guide has further explanations but i will highlight the ones related to the actual solution.

  • Response
    All response serializers (with the exception of response) return a generic Response struct.

  • Response type
    The Result type has been redesigned to be a double generic type that does not store the NSData? in the .Failure case.

Also take in count that Alamofire treats any completed request to be successful, regardless of the content of the response. So you need to chain a .validate() before .responseJSON() to hit the .Failure case. Read more about it here.

Updated code:

let url = "http://api.myawesomeapp.com"
Alamofire.request(.GET, url).validate().responseJSON { response in
    switch response.result {
    case .Success(let data):
        let json = JSON(data)
        let name = json["name"].stringValue
        print(name)
    case .Failure(let error):
        print("Request failed with error: \(error)")
    }
}

For reference:

  • Xcode 7.3 (Swift 2.2)
  • Alamofire 3.3.1
  • SwiftyJSON 2.3.3