Search code examples
iosswiftiphonealamofire

Parsing using in swift using Alamofire 5


I am trying to parse this api response but I am getting this error

"Could not cast value of type '__NSDictionaryI' (0x1e06425d8) to 'NSData' (0x1e06418e0)"

. Here is my code, api response and model class.

class func getCityApi(viewController: UIViewController,
                      completion:@escaping (_ result:[CityDetails])->(),
                      errorHandler:@escaping (_ result:Error,_ statusCode:Int?)->()
) {

    AF.request(KCity, method: .get, parameters: nil, headers: nil).responseJSON { response in
        switch response.result{
        case.success(let data):
            do{
                let jsonData = try JSONDecoder().decode(City.self, from: data as! Data)
                print(jsonData)
                completion(jsonData.data)
            }
            catch{

            }

        case .failure(let error):
            print(error.localizedDescription)
        }
    }
}

Api Response structrue

enter image description here

Model Class

struct City: Codable {
  var data: [CityDetails]
  var status: Bool
  var message: String
}

struct CityDetails: Codable{
  var id: Int
  var location: String
}

Solution

  • You need a Data response. Replace

    AF.request(KCity, method: .get, parameters: nil, headers: nil).responseJSON { response in
    

    with

    AF.request(KCity, method: .get, parameters: nil, headers: nil).responseData { response in
    

    and

    let jsonData = try JSONDecoder().decode(City.self, from: data as! Data)
    

    with

    let jsonData = try JSONDecoder().decode(City.self, from: data)