swiftconcurrencyunusernotificationcenterswift6mainactor

UNUserNotificationCenter UNNotificationSettings non-sendable problem


I'm trying to get the UNAuthorizationStatus from the UNUserNotificationCenter on a MainActor class, but I get a non-sendable error on the UNNotificationSettings.

import UserNotifications

@MainActor
final class Test {
    func aStatus() async -> UNAuthorizationStatus {
        let nCenter = UNUserNotificationCenter.current()
        let settings: UNNotificationSettings = await nCenter.notificationSettings()
        return settings.authorizationStatus
    }
}

The error on the let settings:... line is

Non-sendable result type 'UNNotificationSettings' cannot be sent from nonisolated context in call to instance method 'notificationSettings()'

How do I get the authorizationStatus in a MainActor class?

I can't make UNNotificationSettings Sendable (guess that would be Apples part). I know that I can add @preconcurrency to import UserNotifications to get rid of the error, but I would like to avoid that.


Solution

  • In the case, this function is not accessing any actor isolated state, so you can just make this nonisolated. E.g.:

    @MainActor
    final class Test {
        nonisolated func aStatus() async -> UNAuthorizationStatus {
            await UNUserNotificationCenter.current()
                .notificationSettings()
                .authorizationStatus
        }
    }