When marking the ViewController and the function with @MainActor, the assertion to check that the UI is updated on main thread fails.
How do I guarantee that a function is run on Main Thread when using @MainActor?
Example code:
import UIKit
@MainActor
class ViewController: UIViewController {
let updateObject = UpdateObject()
override func viewDidLoad() {
super.viewDidLoad()
updateObject.fetchSomeData { [weak self] _ in
self?.updateSomeUI()
}
}
@MainActor
func updateSomeUI() {
assert(Thread.isMainThread) // Assertion failed!
}
}
class UpdateObject {
func fetchSomeData(completion: @escaping (_ success: Bool) -> Void) {
DispatchQueue.global().async {
completion(true)
}
}
}
Even changing DispatchQueue.global().async
to Task.detached
does not work.
Tested with Xcode 13.2.1 and Xcode 13.3 RC