iosswiftswift3alamofire

How to request API call repeatedly until get result in swift


I need to know how can I call API repeatedly until get specific status, like 10.

In my case, when I got another result, just call error message in toast. but my team wants to call it repeatedly for purchase process in Appstore.

Below is my code example:

func deliveryProduct(json:JSON, receiptData:String) {

    
    if let _userInfo = Authentication.userInfo {
        if let account = _userInfo.account {

            let dict:[String: Any] = ["myData":data]
            
            getVerifyBillingiOS(dict: dict, completion: {
                value in
            
            let json = JSON(value)

                let myStatus = json["status"].intValue
            
                if myStatus == 10 {
                   print("Result Success")
                }else{
                    print("Result Failed")
                }
                
            })
        }
    }
}


 func postReceiptData(dict: [String: Any], completion: ((Any)->())?) {
    let url = "myServerUrl"
    Alamofire.requestURL(string: url, method: .post, parameter: dict, encoding: JSONEncoding.default, headers: applicationHeader(), completion: {
        success, response in
        
        switch response.result {
        case .success(let value):
            let json = JSON(value)
            
            let status = json["status"].intValue
            print(json["status"])
            print("~~~~~~")
            
            // Success status = 10, failure status = -10
            
            if let _completion = completion {
                _completion(value)
                }
        
        case .failure(let error):
            
            if error._code == NSURLErrorTimedOut {
                Util.showDefaultToast(message: "Network Error")
            }
            
            if let _completion = completion {
                _completion(error.localizedDescription)
            }
        }
    })
}

Solution

  • Instead of

    print("Result Failed")
    

    just recall the function , i can't make it by code because the two functions you mentioned are not related to each other so i can't figure what to do, however recall the function that calls the api instead of printing error (or do both) this will make it keep trying till it works

    Update : after let json = JSON(value)

    you should call

    self.deliveryProduct(json: json, receiptData: receiptData)
    

    and below print("Result Failed") you should call postReceiptData again

    i hope it's clear now