【问题标题】:How to request api call repeatedly until get result in swift如何重复请求 api 调用直到快速得到结果
【发布时间】:2018-09-11 07:52:21
【问题描述】:

我需要知道如何重复调用 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)
            }
        }
    })
}

【问题讨论】:

标签: ios swift api swift3 alamofire


【解决方案1】:

代替

print("Result Failed")

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

更新: 在let json = JSON(value)之后

你应该打电话

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

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

我希望现在很清楚

【讨论】:

  • Alsh,很抱歉打扰您..我尝试使用 deliveryProduct 方法而不是 print,但它不再被调用..!我在其他部分输入如下; self.deliveryProduct(json:json,receiptData:receiptData)
【解决方案2】:

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

示例代码:

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

【讨论】:

    【解决方案3】:

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

    你也可以这样做。

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

    【讨论】:

      【解决方案4】:

      代替

      print("Result Failed")
      

      放这个

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-18
        相关资源
        最近更新 更多