ios - 在 Swift 中按顺序执行任务
问题描述
我正在尝试验证登录并相应地从我的函数返回一个布尔值,但即使我使用异步方法,我的 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
{
}
}
推荐阅读
- knime - Knime 工作流程运行一一设置
- python - 如果重复且对应符合条件,则更改列中的值
- hyperledger-fabric - HyperLedger 结构 java sdk
- perl - 无法在 Mac 上安装 DBD::mysql
- java - 动态表格布局表格行内容不起作用
- python - 悬停在 Kivy ActionBar ActionButton 上
- matlab - 将两位数字添加到路径字符串以读取多个文件时出现问题
- swift - SwiftUI 无法将按钮与 topLeading 对齐
- c# - 尝试对 API 进行身份验证时出现“缺少标头”错误
- python - 在 ProcessPoolExecutor 中捕获 stderr