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



我是 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 !: ")
}
}

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

从以下位置修改函数:

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
}

最新更新