bcye
bcye

Reputation: 845

Why does it matter from where you call DispatchQueue.main.async?

I wrote the following pieces of code:

DispatchQueue.main.async {
    self.cameraManager.checkForCameraAuthorization(deniedCallback: {
        self.presentDeniedAlert()
        self.activityIndicator.stopAnimating()
    }) {
        self.cameraAccess = true
        self.cameraButton.isEnabled = false
        self.activityIndicator.stopAnimating()
    }
}

and

cameraManager.checkForMicrophoneAuthorization(deniedCallback: {
    self.presentDeniedAlert()
        self.activityIndicator.stopAnimating()
    }) {
        DispatchQueue.main.async {
            self.microphoneAccess = true
            self.microphoneButton.isEnabled = false
            self.activityIndicator.stopAnimating()
        }
    }
}

(the difference is from where async is called)

The 1. crashes self.cameraButton.isEnabled = false can only be called from main thread

The 2. one finishes just fine.

Can someone explain, why this is so?

Upvotes: 1

Views: 983

Answers (2)

user10053625
user10053625

Reputation:

Dispatch queues are thread-safe which means that you can access them from multiple threads simultaneously. Always update UI elements from the main queue.

In first code you are updating UI on different threads not from Main Thread.

For more Refrences you can follow these link -

https://www.quora.com/Why-must-the-UI-always-be-updated-on-Main-Thread#

https://www.raywenderlich.com/5370-grand-central-dispatch-tutorial-for-swift-4-part-1-2

Upvotes: 0

vivekDas
vivekDas

Reputation: 1288

The diff is as explained below.

In the 1st code your checkForCameraAuthorization callback is executing in a different thread, and you should know UIApplication/UI related task should execute in the main thread.

In the 2nd code after getting the callback in checkForCameraAuthorization you are executing the UI related task in the main thread, so its works fine.

If any doubt plz comment.

Upvotes: 3

Related Questions