简体   繁体   中英

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 ?

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. :)

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)!)")
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM