如何在从Swift 3中的函数返回结果之前等待URLSession完成 [英] how to wait for the URLSession to finish before returning the result from a function in Swift 3
问题描述
您好我有一个初学者问题,我无法在Swift 3中找到一个好的解决方案。我希望有人能够发牢骚。
Hi i have a beginner question, where i cant find a good solution for in Swift 3. I hope someone is able to hlep.
我有以下代码如果用户凭证有效,将检查休息api。我希望它等待resquest完成然后返回true或false。现在它正在发送异步。
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.
此外,我检查JSON值的方式也会受到欢迎。
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
}
推荐答案
您不能将异步任务中的某些内容作为返回值返回。
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)->() ) {
删除行 var validCredentials = false
和 return validCredentials
用 validCredentials = false
>完成(错误)和
validCredentials = true
完成(true)
。
Replace all occurrences of validCredentials = false
with completion(false)
and
validCredentials = true
with completion(true)
.
调用方法
checkUsernamePassword(username: "Foo", code: "Baz") { isValid in
print(isValid)
// do something with the returned Bool
DispatchQueue.main.async {
// update UI
}
}
这篇关于如何在从Swift 3中的函数返回结果之前等待URLSession完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!