Alamofire Response Serialization Failed

Viewed 4814

I am trying to make an app that uses Stripe and Alamofire for payment processing. I had it working at one point then it just stopped working but Im not sure if it was because of an update or an error. I am also using Heroku to run the backend Nodejs file and I am not getting any errors on the server side and the test payments are going through in Stripe. It is almost like Heroku is not sending the right file type back to my app.

I keep getting this error.

===========Error===========
Error Code: 10
Error Messsage: Response could not be serialized, input data was nil or zero length.
Alamofire.AFError.responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)
===========================

code:

import Foundation
import Stripe
import Alamofire

class StripeClient {

    static let sharedClient = StripeClient()

    var baseURLString: String? = nil

    var baseURL: URL{
        if let urlString = self.baseURLString, let url = URL(string: urlString) {
            print(url)
            return url
        } else {
            fatalError()
        }

    }

    func createAndConfirmPayment(_ token: STPToken, amount: Int, completion: @escaping (_ error: Error?) -> Void) {

        let url = self.baseURL.appendingPathComponent("charge")
        print(url)
        let params: [String : Any] = ["stripeToken" : token.tokenId, "amount" : amount, "description" : Constats.defaultDescription, "currency" : Constats.defaultCurrency]

        AF.request(url, method: .post, parameters: params)
            .validate(statusCode: 200..<300)
            .responseData(completionHandler: { (response) in
                print(response)

                switch response.result {
                case .success( _):
                    print("Payment successful")
                    completion(nil)
                case .failure(let error):
                    if (response.data?.count)! > 0 {print(error)}
                    print("\n\n===========Error===========")
                    print("Error Code: \(error._code)")
                    print("Error Messsage: \(error.localizedDescription)")
                    if let data = response.data, let str = String(data: data, encoding: String.Encoding.utf8){
                        print("Server Error: " + str)
                    }
                    debugPrint(error as Any)
                    print("===========================\n\n")
                    print("error processing the payment", error.localizedDescription)
                    completion(error)
                }

            })

        }
    }

I am using Stripe 18.4, Alamofire 5.0, Xcode 11.3 and Swift 5 Thanks!

2 Answers

This error means that Alamofire unexpectedly had no Data to process when trying to parse a response. You can run debugPrint(response) to see a lot more detail about the response, but this usually occurs when the server returns an empty response without a proper 204 or 205 code (usually a 200) to indicate the response should be empty. If that's the case, and you're running Alamofire 5.2+, you can pass additional empty response codes to your response handler:

AF.request(...)
  .validate()
  .responseData(emptyResponseCodes: [200, 204, 205]) { response in 
    // Process response.
  }

In Alamofire 5.0 to < 5.2, you can customize your response serializer by creating an instance directly:

let serializer = DataResponseSerializer(emptyResponseCodes: Set([200, 204, 205]))

// Use it to process your responses.

AF.request(...)
  .validate()
  .response(responseSerializer: serializer) { response in 
    // Process response.
  }

Firstly check if the data sent from server is valid json may be by running in postman and validating received json.

Or else try sending the encoding type in request. e.g if its JSON or urlEncoded.

for json:

`encoding: JSONEncoding.default`

for url encoded params:

encoding: URLEncoding.default
Related