我正在尝试制作一个使用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谢谢!
[首先检查从服务器发送的数据是否为有效的json,可以通过在邮递员中运行并验证收到的json。
否则,请尝试在请求中发送编码类型。例如其JSON或urlEncoded。
对于json:
`encoding: JSONEncoding.default`
对于url编码的参数:
encoding: URLEncoding.default
此错误意味着Alamofire在尝试解析响应时意外地没有Data
要处理。您可以运行debugPrint(response)
来查看有关响应的更多详细信息,但这通常在服务器返回空响应而没有正确的204或205代码(通常为200)来指示响应应该为空时发生。在这种情况下,您可以通过直接创建实例来自定义响应序列化器:
let serializer = DataResponseSerializer(emptyResponseCodes: Set([200, 204, 205]))
// Use it to process your responses.
AF.request(...)
.validate()
.response(responseSerializer: serializer) { response in
// Process response.
}