本文介绍了Alamofire 响应序列化失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我不断收到此错误.

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

代码:

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

            })

        }
    }

我使用的是 Stripe 18.4、Alamofire 5.0、Xcode 11.3 和 Swift 5谢谢!

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

推荐答案

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

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

在 Alamofire 5.0 中

5.2、你可以通过直接创建一个实例来自定义你的响应序列化器:

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

这篇关于Alamofire 响应序列化失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 23:20