swift - 如何在 swift 中围绕 Alamofire.authenticate 方法制作登录异步函数包装器?
问题描述
我有这个包装类调用AutheManager。它有一个静态函数调用登录一个围绕 Alamofire.authenticate 方法的包装器。我想问我如何实现异步并等待 http 响应完成移动到下一个逻辑
class AutheManager{
var manager: Session!
static func Login(username:String, password:String, completion: @escaping (_ success: Bool, _ response: DataResponse<Data?>?) -> ()) {
var response =
AF.request("https://httpbin.org/basic-auth/\(username)/\(password)")
.authenticate(username: username, password: password)
.response { resp in
response = resp
}
return response
}
}
@IBAction func loginAction(sender: UIButton)
{
// Check that text has been entered into both the username and password fields.
guard let newAccountName = emailTextField.text,
let newPassword = passwordTextField.text,
!newAccountName.isEmpty,
!newPassword.isEmpty else {
showLoginFailedAlert()
return
}
//get response from AutheManager
response = AutheManager.Login(username: newAccountName, password: newPassword)
}
解决方案
在 AutheManager.Login 方法的末尾添加一个闭包
AutheManager.Login(username: String, password: String, completion: @escaping (_ success: Bool, response: [String: Any]?) -> ()) {
...
//call once you get response, for success
completion(true, response)
//for failure
completion(false, nil)
...
}
现在调用这个方法:
AutheManager.Login(username: newAccountName, password: newPassword) { (success, response) in
guard success, let response = response else { //show message }
print(response)
///move you rest of the code/logic here
}
推荐阅读
- code-coverage - 是否有任何工具可以显示 .drl 文件的代码覆盖率?我在 Then 部分有一些分支
- c++ - C++:在头文件中生成常量数组实例
- gpu - 如何使用 Vulkan 有效地计算汉明距离
- swift - macOS 上的 Swift:使用 URL 作为参数打开 Chrome
- javascript - 如何使用 _.set 或等效方法从数组中删除元素
- python - 如何使用 selenium 获取 youtube 视频的标签?
- python - 调用函数时,它告诉我对象(列表)的位置而不是列表本身?
- javascript - 使用 findIndex 检查对象数组中存在的元素数组 - 打字稿
- php - 查找最接近值的数字不起作用(SQL)
- r - 使用 if 语句在 R 中定义函数