如何请求 api 重复调用直到在 swift 中得到结果

How to request api call repeatedly until get result in swift

我需要知道如何重复调用 api 直到获得特定状态,例如 10。

在我的例子中,当我得到另一个结果时,只需在 toast 中调用错误消息即可。 但我的团队想在 Appstore 的购买过程中重复调用它。

下面是我的代码示例。

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

而不是

print("Result Failed")

只记得函数,我不能通过代码实现,因为你提到的两个函数彼此不相关,所以我不知道该怎么做,但是记得调用 api 而不是打印错误(或两者都做)这将使它继续尝试直到它工作

更新: 在 let json = JSON(value)

之后

你应该打电话给

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

及以下print("Result Failed") 你应该再打电话给 postReceiptData

我希望现在已经清楚了

@Fahadsk 建议的解决方案也很好,工作正常。

您也可以按照以下方式进行。

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

一个简单的方法。使用回调获取状态码,检查是否需要一个,否则再次调用函数发出请求。继续此过程,直到获得所需的代码。

示例代码:

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 SomeStruct {
var status:Int?
init(dict: [String:Int])
{
    status = dict["status"]
}}

而不是

print("Result Failed")

放这个

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