How to implement Codable with AFNetworking

315 Views Asked by At

I am working on a mix project of Swift and Objc, AFNetworking is implemented in it for network calls. I created swift file where I want to implement Codable model, but since AFNetworking is responding back in NSDictionary or id format response I am unable to use the decodable. I need a way such that AFNetworking returns me NSData/Data format response object which I can directly use with decodable

1

There are 1 best solutions below

0
gcharita On

Using the default AFHTTPResponseSerializer as your responseSerializer, you will get the response data in the second parameter of the success closure. You just need to type cast it as Data:

let manager = AFHTTPSessionManager()
manager.responseSerializer = AFHTTPResponseSerializer()
manager.get(urlString, parameters: nil, headers: nil, progress: nil, success: { task, object in
    guard let data = object as? Data else { return }
    let decoder = JSONDecoder()
    do {
        let decoded = try decoder.decode(MyType.self, from: data)
        print(decoded)
    } catch {
        print(error)
    }
}, failure: { task, error in
    print(error)
})