2016-11-24 61 views
0

这是块我:如何完成竣工座 - 斯威夫特/条纹付款

func createBackendChargeWithToken(_ token: STPToken, completion: @escaping STPTokenSubmissionHandler) { 
    if backendChargeURLString != "" { 
     if let url = URL(string: "https://wt-lightfalldev-gmail-com-0.run.webtask.io/stripe-payment/payment") { 
      let chargeParams : [String: AnyObject] = ["stripeToken": token.tokenId as AnyObject, "amount": shirtPrice as AnyObject] 

      Alamofire.request(url, method: .post, parameters: chargeParams, encoding: JSONEncoding.default, headers: heads).responseJSON { (response:DataResponse<Any>) in 

       switch(response.result) { 
       case .success(_): 
        if response.result.value != nil{ 
         print(response.result.value!) 
        } 
        break 

       case .failure(_): 
        print(response.result.error!) 
        break       
       } 
      } 
     } 
    } 
    completion(STPBackendChargeResult.failure, NSError(domain: StripeDomain, code: 50, userInfo: [NSLocalizedDescriptionKey: "You created a token! Its value is \(token.tokenId!). Now configure your backend to accept this token and complete a charge."])) 
} 

但是这需要在它,但我不知道如何将其正确写入:

if (error) { 
    completion(STPBackendChargeResultFailure, error); 
} else { 
    completion(STPBackendChargeResultSuccess, nil); 
} 

该代码始终使用STPBackendChargeResult.failure调用完成回调。所以它需要是一个if语句,我需要根据Alamofire请求将令牌发送到后端服务器的结果,使用failuresuccess来调用完成回调。

回答

1

为什么你不能把它放在开关?

switch(response.result) { 
case .success(_): 
    if response.result.value != nil{ 
     print(response.result.value!)    
    } 
    completion(STPBackendChargeResultSuccess, nil) 
case .failure(_): 
    print(response.result.error!) 
    completion(STPBackendChargeResultFailure, error) 
} 
+0

如果我把它放在开关中,我会在“pay”按钮上看到一个永不结束的加载标志。所以没有这个不行。 – Manny

+0

在任何情况下,完成回调都应该在alamofire方法的响应块中,您只需知道是否存在错误。您可以尝试将代码的第二部分(if语句)放在交换机上。完成处理程序中的代码也可能有问题。 – ovejka

+0

此外,作为一个想法,如果你在完成块内部有一些UI更新代码,你需要将它分派到主线程(可能是这个+我的答案会一起工作)。 – ovejka