Search code examples
swiftnsoperationqueue

Why doesn't work NSOperationQueue.mainQueue?


I have this code

    @IBAction func joinButtonTouch(sender: AnyObject) {
    NSOperationQueue.mainQueue().addOperationWithBlock({
        self.joinButton.backgroundColor = UIColor(red: 0/255, green: 122/255, blue: 255/255, alpha: 1.0)
        self.activityIndicator.startAnimating()
        self.resultLogIn.text = "Checking data..."
        })


    var response = NetworkManager.sharedInstance.SendRequest("<Command=LogIn><Login=\(loginTextField.text!)><Password=\(passwordTextField.text!)>")
}

And I want that activityIndicator running BEFORE start SendRequest method. But this didn't work. Why? activityIndicator running when SendRequest finished.


Solution

  • You are blocking the main thread with your SendRequest. You have also scheduled your operation to start the indicator, but it's on the queue after the thing which is currently happening, so it isn't going to run until after you release the main thread.

    So, don't put the indicator change into an operation, put the SendRequest into an operation and execute it on a queue that isn't main - i.e. a background thread. Then everything will work smoothly and the users will be happy.