0

I'm trying to verify a login and return a boolean value from my function accordingly, but my return statement keeps getting executed before the web service function is completed, even if I use an async method. I am using both Alamofire and SwiftyJSON.

I'm attaching my code below. Any help would be appreciated!

Thanks.

func checkUs (name: String, password: String)  -> Bool
    {

        bool authen = false
        DispatchQueue.global(qos: .userInitiated).async {

        let jsonDic : [String: String] = ["email": name, "pass": password]
        Alamofire.request("enter URL here", method: .post, parameters: jsonDic, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in
                switch(response.result) {
                case .success(let sentJSON):
                    let gotJSON = JSON (sentJSON)
                    print (gotJSON[0]["status"].boolValue)
                    authen = gotJSON[0]["status"].boolValue
                case .failure(let err):
                    print(err)
                }

            print ("First ", authen)
        }
        }
        print ("Second", authen)

        return authen
        //return true

Log Output:

Second false
true
First true

Raju Thonde
  • 53
  • 1
  • 1
  • 4
  • You said: "...my return statement keeps getting executed before the web service function is completed, even if I use an async method. " That is **THE WHOLE POINT** with async methods. They return before the desired action has completed. See the link rmaddy gave you when he closed the question as a duplicate. – Duncan C May 09 '18 at 17:12

1 Answers1

0

You need completion , also Alamfire runs asynchronously no need for global queue

func checkUs (name: String, password: String,completion: @escaping (_ status: Bool,_ err:Error?) -> Void) {

        bool authen = false

        let jsonDic : [String: String] = ["email": name, "pass": password]
        Alamofire.request("enter URL here", method: .post, parameters: jsonDic, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in
                switch(response.result) {
                case .success(let sentJSON):
                    let gotJSON = JSON (sentJSON)
                    print (gotJSON[0]["status"].boolValue)
                    authen = gotJSON[0]["status"].boolValue
                     completion(authen,nil)
                case .failure(let err):
                    print(err)
                    completion(authen,err)
                }

            print ("First ", authen)

        }
        print ("Second", authen)

     }

//

call it like this

self.checkUs(name: "endedName", password: "sendedPassword") { (status, error) in

    if let err = error {


    }
    else
    {

    }
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • 1
    You've answered similar questions many times. Please consider voting to close as a duplicate instead of answering every time. – rmaddy May 09 '18 at 16:27