2016-11-24 60 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