Why does it matter from where you call DispatchQueue.main.async?
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
self.cameraButton.isEnabled = false can only be called from main thread
The 2. one finishes just fine.
Can someone explain, why this is so?
2 Answers
2
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.
checkForCameraAuthorization
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.
checkForCameraAuthorization
If any doubt plz comment.
Yes right, you submitted entire task into main queue, but that doesn't mean callback will also happen in the main queue.
– vivekDas
Sep 16 '18 at 17:54
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
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy
So that the function is called from .main.async doesn't mean that the callback is called in this thread? E.g. the callback is still not called from .main.async, right?
– Bruce
Sep 16 '18 at 17:34