Vandan Patel
Vandan Patel

Reputation: 1022

Make main thread wait until URLRequest finishes

I am trying to hold execution until URLRequest is done.

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
    self.sendRequest(request: request as URLRequest) {
        }
    self.firebaseAuth(credential)
    self.performSegue(withIdentifier: SEGUE_TO_FIRST_CONTENT_PAGE, sender: nil)

}

func sendRequest (request: URLRequest, completion: @escaping () -> ()) {
    let session = URLSession.shared

    session.dataTask(with: request as URLRequest) { (data, response, error) in
        UIApplication.shared.isNetworkActivityIndicatorVisible = false
        do {
            let userData = try JSONSerialization.jsonObject(with: data!, options:[]) as? [String:AnyObject]
            let genderData = userData!["gender"] as! String
            self.userObject.gender = genderData
            completion()
        } catch {
            completion()
            print("ERROR")
        }
        print("sendRequest Done!")
        }.resume()
}

Right now, it performs segue even before finishing sendRequest(). I can't figure out how to make main thread wait til sendRequest() is done.

Upvotes: 0

Views: 190

Answers (1)

user3608500
user3608500

Reputation: 835

Modify the completion handler to pass the request status and perform action in completion handler based on the status.If the operation is anything to do with UI , then wrap that in main thread.Sample below

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
    self.sendRequest(request: request as URLRequest){ (loginStatus) in
        if loginStatus {
            DispatchQueue.main.async {
            self.firebaseAuth(credential)
            self.performSegue(withIdentifier: SEGUE_TO_FIRST_CONTENT_PAGE, sender: nil)
            }
        }
        else{
            //Handle Error case
        }
    }

}

func sendRequest (request: URLRequest, completion: @escaping (Bool) -> ()) {
    let session = URLSession.shared

    session.dataTask(with: request as URLRequest) { (data, response, error) in
        UIApplication.shared.isNetworkActivityIndicatorVisible = false
        do {
            let userData = try JSONSerialization.jsonObject(with: data!, options:[]) as? [String:AnyObject]
            let genderData = userData!["gender"] as! String
            self.userObject.gender = genderData
            completion(true)
        } catch {
            completion(false)
            print("ERROR")
        }
        print("sendRequest Done!")
        }.resume()
}

Upvotes: 1

Related Questions