MainActor and NSInternalInconsistencyException: 'Call must be made on main thread'

Hello,

When attempting to assign the UNNotificationResponse to a Published property on the main thread inside UNUserNotificationCenterDelegate's method

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async

both Task { @MainActor in } and await MainActor.run are throwing a NSInternalInconsistencyException: 'Call must be made on main thread'.

I thought both of them were essentially doing the same thing, i.e. call their closure on the main thread. So why is this exception thrown? Is my understanding of the MainActor still incorrect, or is this a bug?

Thank you


Note: Task { await MainActor.run { ... } } and DispatchQueue.main.async don't throw any exception.

Hi,

I just ran into the same issue. However our app still crashed when the delegate method was empty and the user tapped on the notification on the Lock Screen while the app was in the foreground.

For us switching back to the old completion based delegate method solved the issue.

After a little bit of digging we found a proper solution for the problem.

You need to mark the delegate method with @MainActor like:

@MainActor
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {

    // Do your stuff

}
11

Deleted

MainActor and NSInternalInconsistencyException: 'Call must be made on main thread'
 
 
Q