Marie Arkan
Marie Arkan

Reputation: 55

How to convert <AnyObject> response in AnyObject after an Alamofire request with JSON in Swift?

So I want to send a request to a specific API which is supposed to return a JSON file.

I am using Alamofire in order to get the JSON object :

dataFromAPI : JSON
Alamofire.request(.GET, myURL).responseJSON { (_, _, data) -> Void in
               dataFromAPI = JSON(data)
            }

My problem is that data is an array of AnyObject and the JSON function needs an AnyObject type. How can I transform one into another or resolve the problem ?

Upvotes: 1

Views: 723

Answers (2)

Jonauz
Jonauz

Reputation: 4133

Not sure if I got your question, but will try to provide you an example of how I do it. Changed code to your case.

Alamofire.request(.GET, myURL)
    .validate(statusCode: 200..<300)
    .validate(contentType: ["application/json"])
    .responseJSON { request, response, jsonResult in
        switch jsonResult {
        case .Success:
            if let data = jsonResult.value as? AnyObject {
                self.dataFromAPI = JSON(data)
            }
        case .Failure(_, let error):
            print(error)
        }
}

Normally I wouldn't do unwrapping to AnyObject, as it makes little sense. I usually unwrap to [String: AnyObject] as I'm expecting Dictionary from my API, and then I attempt to convert it to my custom model class.

Correct me if I miss-understood the question. :)

Upvotes: 3

redent84
redent84

Reputation: 19249

Alamofire returns a Result<AnyObject> object. You should check if the result is a success or a failure before extracting the JSON:

Alamofire.request(.GET, myURL)
    .responseJSON { request, response, result in
        switch result {
        case .Success(let JSON):
            print("Success with JSON: \(JSON)")

        case .Failure(let data, let error):
            print("Request failed with error: \(error)")

            if let data = data {
                print("Response data: \(NSString(data: data, encoding: NSUTF8StringEncoding)!)")
            }
        }
    }

Upvotes: 0

Related Questions