我正在尝试验证登录并相应地从我的函数返回 bool 值,但即使我使用异步方法,我的 return 语句也会在 Web 服务函数完成之前不断执行。我同时使用 Alamofire 和 SwiftyJSON。
我在下面附上了我的代码。任何帮助将不胜感激!
谢谢。
func checkUs (name: String, password: String) -> Bool
{
bool authen = false
DispatchQueue.global(qos: .userInitiated).async {
let jsonDic : [String: String] = ["email": name, "pass": password]
Alamofire.request("enter URL here", method: .post, parameters: jsonDic, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in
switch(response.result) {
case .success(let sentJSON):
let gotJSON = JSON (sentJSON)
print (gotJSON[0]["status"].boolValue)
authen = gotJSON[0]["status"].boolValue
case .failure(let err):
print(err)
}
print ("First ", authen)
}
}
print ("Second", authen)
return authen
//return true
日志输出:
第二个错误
正确
第一个真实
最佳答案
您需要完成,而且Alamfire异步运行,不需要全局队列
func checkUs (name: String, password: String,completion: @escaping (_ status: Bool,_ err:Error?) -> Void) {
bool authen = false
let jsonDic : [String: String] = ["email": name, "pass": password]
Alamofire.request("enter URL here", method: .post, parameters: jsonDic, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in
switch(response.result) {
case .success(let sentJSON):
let gotJSON = JSON (sentJSON)
print (gotJSON[0]["status"].boolValue)
authen = gotJSON[0]["status"].boolValue
completion(authen,nil)
case .failure(let err):
print(err)
completion(authen,err)
}
print ("First ", authen)
}
print ("Second", authen)
}
//
这样称呼
self.checkUs(name: "endedName", password: "sendedPassword") { (status, error) in
if let err = error {
}
else
{
}
}
关于ios - 在 Swift 中顺序执行任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50257326/