如何围绕 swift 中的 Alamofire.authenticate 方法制作登录异步函数包装器?
how to make login async function wrapper around Alamofire.authenticate method in swift?
我有这个包装器 class 调用 AutheManager。它有一个静态函数调用 Login a wrapper around Alamofire.authenticate method.I 想问我如何实现异步并等待 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
}
我有这个包装器 class 调用 AutheManager。它有一个静态函数调用 Login a wrapper around Alamofire.authenticate method.I 想问我如何实现异步并等待 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
}