I am updating a Network Foundation to Swift (and Alamofire) Version 5.
One method that should provide "Generic Response Object Serialization" is throwing the error
Cannot specialize non-generic type 'DataResponseSerializer'
I think in Alamofire 5 they made the Type DataResponseSerializer non-generic. Any ideas how to achieve the same behavior in the newest version? Unfortunately I am not very familiar neither with Alamofire nor Generics.
public extension Alamofire.DataRequest {
@discardableResult
func responseDecodableObject<T: Decodable>(completionHandler: @escaping (DataResponse<T>) -> Void) -> Self {
//error is thrown here
let responseSerializer = DataResponseSerializer<T> { request, response, data, error in
guard error == nil else { return .failure(error!) }
let result = DataRequest.jsonResponseSerializer(options: .allowFragments).serializeResponse(request, response, data, error)
switch result {
case .success(let value):
do {
let data = try JSONSerialization.data(withJSONObject: value, options: .prettyPrinted)
return .success(try JSONDecoder().decode(T.self, from: data))
} catch {
return .failure(ErrorSerializer.JSONDecoderFailed(json: "\(value)", errorText: error.localizedDescription))
}
case .failure(let error):
return.failure(error)
}
}
return response(responseSerializer: responseSerializer, completionHandler: completionHandler)
}
}
I found many Tutorials that show ways to achieve this, but all of them share the generic DataResponseSerializer. For example: Medium
You're correct, DataResponseSerializer is no longer generic in Alamofire 5.
More importantly, Alamofire now has support for Decodable built in with responseDecodable and DecodableResponseSerializer, so you don't need to write it yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With