等待响应结果再进行下一步代码iOS swift

问题描述 投票:0回答:1

我是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 !: ")
                }
}
ios swift iphone alamofire
1个回答
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
}
© www.soinside.com 2019 - 2024. All rights reserved.