how to wait for the URLSession to finish before returning the result from a function in Swift 3

ε祈祈猫儿з 提交于 2019-12-05 07:15:38

问题


Hi i have a beginner question, where i cant find a good solution for in Swift 3. I hope someone is able to hlep.

i have the following code that will check a rest api if the user credentials are valid or not. I want it to wait for the resquest is finished and then return true or false. now it is being send async.

Also any improvement in the way i check the JSON value's would be welcome too.

func CheckUsernamePassword(username :String ,code:String )-> bool {

    var validCredentials = false


    let urlString = "\(self.baseurl)/accounts/validateusernamepassword.json?username=\(username)&password=\(code)&api_key=\(self.api_key)"

    let url = URL(string: urlString)
    URLSession.shared.dataTask(with:url!) { (data, response, error) in
        if error != nil {
            print("Error URLSession : \(error!)")
            validCredentials = false
        } else {
            do {
                let parsedData = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]

                if parsedData["validated"] != nil {
                    if "\(parsedData["validated"]!)" == "1" {
                        print("Login credentials are correct")
                        validCredentials = true             
                    }else {
                        print("Login credentials are not correct")
                        print("\(parsedData["validated"]!)")
                        print("\(parsedData["message"]!)")
                        validCredentials = false
                    }
                }else{
                    print("Json Parse error: \(parsedData)")
                    validCredentials = false
                }
            } catch let error as NSError {
                print("Error Parsing Json \(error)" )
                validCredentials = false
            }
        }

        }.resume()
    return validCredentials          
}

回答1:


You cannot return something from an asynchronous task as a return value.

Do not wait, use a completion handler:

  • Replace the signature of the method (the name is supposed to start with a lowercase letter) with

    func checkUsernamePassword(username: String, code: String, completion: @escaping (Bool)->() ) {
    
  • Delete the lines var validCredentials = false and return validCredentials

  • Replace all occurrences of validCredentials = false with completion(false) and validCredentials = true with completion(true).

  • Call the method

    checkUsernamePassword(username: "Foo", code: "Baz") { isValid in
        print(isValid)
        // do something with the returned Bool
        DispatchQueue.main.async {
           // update UI
        }
    }
    


来源:https://stackoverflow.com/questions/42804320/how-to-wait-for-the-urlsession-to-finish-before-returning-the-result-from-a-func

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!