responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)

Viewed 2166

I have a API with post method and following is the code for it

func addScheduleService() {
      let parameter = ["start_time":"06:00","end_time":"09:00","schedule_date":"07/23/2020","schedule_id":"0"]
                      
                      print("parameter is",parameter)
        
       let header: HTTPHeaders = ["Content-Type":"application/json","x-token": self.token!]

 AF.request(mainURL+URLS.addschedule.rawValue, method: .post, parameters: parameter, encoding: JSONEncoding.default, headers: header)
        .responseJSON {
            response in
            switch response.result {
            case .success(let json):
                print("value is",json)
            case .failure(let error):
                print("error is",error)}
            }
        }

The response in the postman is as follows:

enter image description here

The output from the code is responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)

What could be the error?

2 Answers

.inputDataNilOrZeroLength means you got an empty response without a 204 or 205 response code, so Alamofire considers the response invalid (empty bodies are only valid for 204 or 205 responses). If this is expected, you'll need to add the expected status code to the list of acceptable empty response codes in responseDecodable:

AF.request(...).responseDecodable(of: YourType.self,
                                  emptyResponseCodes: [200, 204, 205]) { response in

}

Perhaps you might have a look to this answer -> GitHub Alamofire-responseSerializationFailed

It looks like the server response has an empty body, so Alamofire will receive it, as it is.

Alamofire will look after the result code, and will find 200, but with an empty body. And may not be considered as valid, for an empty response.

Go with number 1 if you can act on server side.

1 - Change server response to proper 204 - empty

2 - Create your own DataResponseSerializer:

let dataResponseSerializer = DataResponseSerializer(emptyResponseCodes: [200, 204, 205]) // Default is [204, 205]
manager.upload(multipartFormData: { multipartFormData in
        /// ...
    }, usingThreshold: UInt64.init(), to: ep.s3.virginiaBucketUrl, method: .post, headers: headers)
    .response(responseSerializer: dataResponseSerializer) { response in
        switch response.result {
            case .failure(let error):
                // ...
            case .success(let value):
                // ...
        }
    }
Related