Alamofire 响应序列化失败

hay*_*den 3 json stripe-payments swift alamofire

我正在尝试制作一个使用 Stripe 和 Alamofire 进行支付处理的应用程序。我曾经让它工作过,然后它就停止工作了,但我不确定这是因为更新还是错误。我还使用 Heroku 运行后端 Nodejs 文件,并且在服务器端没有收到任何错误,并且测试付款正在 Stripe 中进行。这几乎就像 Heroku 没有将正确的文件类型发送回我的应用程序。

我不断收到此错误。

===========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)
===========================

Run Code Online (Sandbox Code Playgroud)

代码:

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)
                }

            })

        }
    }
Run Code Online (Sandbox Code Playgroud)

我正在使用 Stripe 18.4、Alamofire 5.0、Xcode 11.3 和 Swift 5 谢谢!

Jon*_*ier 6

此错误意味着 AlamofireData在尝试解析响应时意外地无法处理。您可以运行debugPrint(response)来查看有关响应的更多详细信息,但这通常发生在服务器返回空响应而没有正确的 204 或 205 代码(通常是 200)来指示响应应该为空时。如果是这种情况,并且您正在运行 Alamofire 5.2+,您可以将其他空响应代码传递给您的响应处理程序:

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

在 Alamofire 5.0 到 < 5.2 中,您可以通过直接创建实例来自定义响应序列化器:

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

// Use it to process your responses.

AF.request(...)
  .validate()
  .response(responseSerializer: serializer) { response in 
    // Process response.
  }
Run Code Online (Sandbox Code Playgroud)