简体   繁体   中英

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

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

Solution suggested by @Fahadsk is also good and working fine. reference

You can also do as below.

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

           let myStatus = (json["status"]

           if myStatus == 10 {
               print("Result Success")
            }else{
            // Call your method again
                postReceiptData(your argument)
            }

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

An easy approach. Get the status code using call back, check if it is required one, else call the function making request again. Keep this process going until you get the desired code.

Sample code:

func getData()
{
    requestForDataWithURL(url: "http://localhost:8000/getData") { (code) in
        if code == 200
        {
            print("success")
        }
        else
        {
            self.getData()
        }
    }
}

func requestForDataWithURL(url:String, completionHandler: @escaping (_ statusCode: Int)->Void)
{
    var request = URLRequest.init(url: URL.init(string: url)!)
    request.httpMethod = "POST"
    let dataTask = URLSession.shared.dataTask(with: request) { (data, response, error) in
        if data != nil
        {
            do{
                let responseDict = try JSONSerialization.jsonObject(with: data!, options: [])
                let someStruct = SomeStruct.init(dict: responseDict as! [String : Int])
                print(someStruct)
                completionHandler(someStruct.status!)
            }catch
            {

            }

        }
    }
    dataTask.resume()
}

Struct used in above code

struct SomeStruct {
var status:Int?
init(dict: [String:Int])
{
    status = dict["status"]
}}

Instead of

print("Result Failed")

Put this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM