gpt4 book ai didi

json - Alamofire 响应序列化失败

转载 作者:行者123 更新时间:2023-12-05 02:08:46 25 4
gpt4 key购买 nike

我正在尝试制作一个使用 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)
===========================

代码:

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谢谢!

最佳答案

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

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

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

关于json - Alamofire 响应序列化失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60579392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com