-1

I have a method that returns a bool (defaulted to false) and uses Alamofire to call an API which return a string. However, as the API request is asynchronous, the method always completes and returns false before the async request is finished. How can I wait till the API call is 'actually' complete in order to return the correct result?

I've tried putting the return statement within the .success and .failure blocks but that causes an error

func validateCredentials() -> Bool{
    var apiResult = false

Alamofire.request("http://myURL?pUser=\(usernameTextField.text!)&pPwd=\(passwordTextField.text!)&pCheckIt=y")
        .responseString {
            response in
            switch response.result{
            case .success:
                apiResult = true

            case .failure:
                apiResult = false
            }
    }

    ProgressHUD.show("Please wait...")

    return apiResult . <==== Always return false

}
  • 1
    Possible duplicate of [Returning data from async call in Swift function](https://stackoverflow.com/questions/25203556/returning-data-from-async-call-in-swift-function) – vadian Sep 10 '19 at 13:32

1 Answers1

0

You need to put escaping completion block Like below.

func validateCredentials(completion:@escaping(Bool) -> Void) {
        ProgressHUD.show("Please wait...")
        Alamofire.request("http://myURL?pUser=\(usernameTextField.text!)&pPwd=\(passwordTextField.text!)&pCheckIt=y")
            .responseString {
                ProgressHUD.hide()
                response in
                switch response.result{
                case .success:
                    completion(true)
                case .failure:
                    completion(false)
                }
        }

    }
Hitesh
  • 896
  • 1
  • 9
  • 22