代码之家  ›  专栏  ›  技术社区  ›  Hanryang

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

  •  0
  • Hanryang  · 技术社区  · 6 年前

    我需要知道如何反复调用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)
                }
            }
        })
    }
    
    4 回复  |  直到 6 年前
        1
  •  1
  •   Mostafa Sultan Tono Nam    6 年前

    而不是

    print("Result Failed")
    

    只需调用函数,我无法通过代码实现它,因为您提到的两个函数彼此不相关,所以我不知道该怎么做,但是调用调用api的函数,而不是打印错误(或同时执行这两种操作),这将使它不断尝试,直到成功

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

    你应该打电话

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

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

    我希望现在清楚了

        2
  •  1
  •   Pallav Trivedi    6 年前

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

    示例代码:

    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
  •  0
  •   Hitesh Surani    6 年前

    @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
  •  0
  •   Manish Mahajan    6 年前

    而不是

    print("Result Failed")
    

    放这个

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