如何在swift中围绕Alamofire.authenticate方法创建登录异步函数包装器?
我有一个包装器类,叫做AutheManager。它有一个静态函数调用Login,一个围绕Alamofire.authenticate方法的包装器如何在swift中围绕Alamofire.authenticate方法创建登录异步函数包装器?,swift,asynchronous,alamofire,httpresponse,Swift,Asynchronous,Alamofire,Httpresponse,我有一个包装器类,叫做AutheManager。它有一个静态函数调用Login,一个围绕Alamofire.authenticate方法的包装器 class AutheManager{ var manager: Session! static func Login(username:String, password:String, completion: @escaping (_ success: Bool, _ response: DataResponse<Data?&g
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
}
请注意,您实际上并没有登录到任何地方。您只需获得一个用户密码凭据。然后将其提供给Alamofire,Alamofire仅在使用基本身份验证或摘要身份验证时使用它。