首页 > 解决方案 > 如何在 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)

    }   

标签: swiftasynchronousalamofirehttpresponse

解决方案


在 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

}

推荐阅读