在继续下一个代码iOS swift之前等待响应结果

Posted

技术标签:

【中文标题】在继续下一个代码iOS swift之前等待响应结果【英文标题】:Wait response result before proceeding next code iOS swift 【发布时间】:2020-06-03 12:03:17 【问题描述】:

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

【问题讨论】:

这能回答你的问题吗? Returning data from async call in Swift function 【参考方案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

【讨论】:

以上是关于在继续下一个代码iOS swift之前等待响应结果的主要内容,如果未能解决你的问题,请参考以下文章

NSURLSession 响应字符串完成块 - Swift

高性能编程之协程--------asyncio

如何在从 Swift 3 中的函数返回结果之前等待 URLSession 完成

同步异步阻塞非阻塞 总结

在使用 Swift 的 iOS 应用程序中使用 DispatchQueue 等待数据从 Cloud Firestore 返回时遇到问题

如何使用事件发射器调用返回值的函数,并在继续之前等待响应?