等待响应结果,然后继续执行下一个代码iOS swift

时间:2020-06-03 12:03:17

标签: ios swift iphone alamofire

我是iOS swift的初学者。
我有一个问题:当我发出网络请求时,编译器无需等待服务器响应即可执行以下代码。

func callingRiderLoginCopy(userID: String, Password:String, completeCode: Int)  {


    print("I am in callingRiderLoginCopy And Complete verification Code is \(completeCode)")


    let parameters : [String : Any] = ["userId": userID, "password": Password, "verificationCode": completeCode]

    guard let url = URL(string: "\(Constents.baseURL)/rider/logIn") else {
        print("Invalid URL")
        return
    }


    AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default)
        .responseJSON { response in
            switch response.result {
            case .success:
                if let result = response.data {
                    do {

                        let resultIs = try JSONDecoder().decode(RiderLoginCopy.self, from:result)
                        self.riderSuc = resultIs.success // Strore the success state in riderSuc

                        print("Data is riderSuc ** \(self.riderSuc)")

                        if let results = resultIs.user {

                            print("This data came from RiderLoginCopy API : \(resultIs)")

                            self.setToken = KeychainWrapper.standard.set(resultIs.token!, forKey: "token")
                            self.retrivedToken = KeychainWrapper.standard.string(forKey: "token")!
                            print("Retrived Token ::: \(self.retrivedToken)")

                        }

                    } catch {
                        print(error)

                    }

                }

            case .failure(let error):
                print(error)

            }            
    }

}


@IBAction func verifyAct(_ sender: UIButton) {

    let userId = enteredUserID
    KeychainWrapper.standard.string(forKey: "Password")!
    let password = enteredPassword
    KeychainWrapper.standard.string(forKey: "UserID")!

    let completeCode:Int = Int(textField1.text! + textField2.text! + textField3.text! + textField4.text!)!

        self.callingRiderLoginCopy(userID: userId, Password: password, completeCode: completeCode)

        if self.riderSuc == 1 {

                    let storyboard = UIStoryboard(name: "Rider", bundle: nil)
                    let vc = storyboard.instantiateViewController(withIdentifier: "signin2VC") as! SignIn2VC
                vc.verifyCode = completeCode
                    self.navigationController?.pushViewController(vc, animated: true)

                }else{
                    print("Plese Try Try again RiderSuc is not equal to 1 !: ")
                }
}

1 个答案:

答案 0 :(得分:0)

在类型completionHandler:的函数定义中使用闭包(String?) -> Void参数来知道何时收到响应,然后继续其余代码。

从以下位置修改您的功能

func callingRiderLoginCopy(userID: String, Password: String, completeCode: Int) {

对此:

func callingRiderLoginCopy(userID: String, Password:String, completeCode: Int, completionHandler: @escaping (String?) -> Void)  {

如果成功接收到retrivedToken,则返回nil,否则返回self.callingRiderLoginCopy(userID: userId, Password: password, completeCode: completeCode)

当您调用此方法时,请从以下位置修改您的调用:

self.callingRiderLoginCopy(userID: userId, Password: password, completeCode: completeCode) { token in
    // Do stuff related to token
}

对此:

function copyRows()
{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var srcSheet = ss.getSheetByName("Form Responses 1");
  var tarSheet = ss.getSheetByName("MasterDB");
  var lastRow  = srcSheet.getLastRow();
  var Lr       = tarSheet.getLastRow();
  for (var i = 2; i <= lastRow; i++) 
  {
    var cell = srcSheet.getRange("A" + i);
    var val = cell.getValue();
    Logger.log(lastRow)
    
        for(var j=2; j<= Lr; j++)
    
      {
    
        var findstring = tarSheet.getRange("A" + j);
        var find =findstring.getValue();
       // Logger.log(find)
       
      if (val == find) 
       {
        continue;
        }
var srcRange = srcSheet.getRange("A" + i + ":T" + i);
            var tarRow = tarSheet.getLastRow();
            tarSheet.insertRowAfter(tarRow);
            var tarRange = tarSheet.getRange("A" + (tarRow+1) + ":T" + (tarRow+1));
            srcRange.copyTo(tarRange);
 }
}
}