iosswiftalamofirealamofire5

Alamofire EmptyResponseCodes doesn't work


Endpoint responds with code 201 and an empty response body. Looking through the Alamofire documentation there is only 204 and 205 response body can be empty. There is a solution that we can specify status code with empty results. Added set of

emptyResponseCodes: [200, 201, 202, 203, 204, 205]

and after sending a request, I still get an error != nil What I am doing wrong here?

responseDecodable(of: TResult.self,
                  decoder: self.jsonDecoder,
                  emptyResponseCodes: [200, 201, 202, 203, 204, 205],
                  completionHandler: { (response: DataResponse<TResult, AFError>) in
                                    
                                    if let error = response.error {
                                        taskCompletionSource.set(error: error)
                                    } else if let result = response.value {
                                        taskCompletionSource.set(result: result)
                                    } else {
                                        taskCompletionSource.set(result: EmptyCodable())
                                    }

Solution

  • Alamofire includes an Empty type for exactly this purpose, as well as an EmptyResponse protocol so that types can define their own empty value. In our included response serializers we check to see if an empty response is allowed, and, if so, attempt to cast the relevant empty type.

    For example:

    struct EmptyEntity: Codable, EmptyResponse {
        
        static func emptyValue() -> EmptyEntity {
            return EmptyEntity.init()
        }
    }