Search code examples
swiftnetwork-programmingalamofire

How to wait until networking by Alamofire has finished?


I'd like to wait until networking by Alamofire has finished.

However, with the present code, it won't wait the finishing of networking, then move to next page by login() function.

Could you tell me how to wait until netwokirng by Alamofire finished?

@IBAction func signInWithTwitter(sender: UIButton) {

    Twitter.sharedInstance().logInWithCompletion { (session: TWTRSession!, error: NSError!) -> Void in
        if session != nil {
            let parameters = [
                "tw_id":session.userID,
                "tw_name" :session.userName,
                "tw_token":session.authToken
            ]

            Alamofire.request(.POST, self.uri.usersApi + "/tw_login", parameters: parameters, encoding: .JSON)
                .responseJSON { (request, response, data, error) in
                    var jsonObj = JSON(data!)
                    var uid = jsonObj["user_id"].int
                    self.defaults.setObject(uid, forKey: "uid")
            }

            self.login()

        } else {
            println(error.localizedDescription)
        }
    }
}

Solution

  • Try to put the login method inside the Alamofire block

    Alamofire.request(.POST, self.uri.usersApi + "/tw_login", parameters: parameters, encoding: .JSON)
        .responseJSON { (request, response, data, error) in
            var jsonObj = JSON(data!)
            var uid = jsonObj["user_id"].int
            self.defaults.setObject(uid, forKey: "uid")
            self.login()
    }