Manny
Manny

Reputation: 91

How To Finish Completion Block - Swift / Stripe Payments

This is the block I have:

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."]))
}

but this needs to be in it but I don't know how to write it correctly:

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

The code is always calling the completion callback with STPBackendChargeResult.failure. So it needs to be an if statement and I need to call the completion callback with either failure or success depending on the result of the Alamofire request to send the token to the backend server.

Upvotes: 0

Views: 685

Answers (1)

ovejka
ovejka

Reputation: 999

Why can't you just put it in the switch?

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

Upvotes: 1

Related Questions