Doz
Doz

Reputation: 7149

Alamofire and responseJSONDecodable with either Dictionary or Array type

I am working with Swift and Alamofire to access an API. I am using code similar to the following:

Almofire.request(url!, method: HTTPMethod.get, parameters: nil, encoding: JSONEncoding.default, headers: headers).validate() .responseJSONDecodable { (response: DataResponse<[GeoEntity]>) in

        response.result.ifFailure({
            let responseError = try? AUAPIError(response)
            guard (responseError?.type == nil) else{
                //if we get .InvalidGrant, get new token by logging in the normal way.
                if (responseError?.type == .UnauthorizedClient){
                    AUService.shared.delegate?.unAuthorizedAccess(error: responseError!)
                    completion(nil, responseError)
                }
                return
            }
        })

        response.result.ifSuccess({
            completion(response.result.value, nil)
        })

    }

``` The problem I am facing is that DataResponse<[GeoEntity]> can either return an array of GeoEntity objects, or a single one as a dictionary. Using Alamofire 5 and responseJSONDecodable, how do I cater to both kinds that are returned. Or do I have to resort to the older way of decoding?

Upvotes: 1

Views: 605

Answers (1)

Varsha Parmar
Varsha Parmar

Reputation: 92

Please Check for type like

 if response is NSArray{ 
//if type is array
} 
 if response is NSDictionary
{ //if type is Dictionary
}

Upvotes: 1

Related Questions