Search code examples
iosswift3xcode9swxmlhash

Cannot assign 'AppDelegate' to 'UNUserNotificationCenterDelegate'


I'm following this tutorial: https://medium.com/flawless-app-stories/ios-remote-push-notifications-in-a-nutshell-d05f5ccac252

But for some reason, I'm getting

cannot assign 'AppDelegate' to 'UNUserNotificationCenterDelegate'.

What does that line do? If I comment it out, the rest of the code works and the user is prompted if they want to allow notifications.

func registerForPushNotifications() {
    UNUserNotificationCenter.current().delegate = self // line in question
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
        (granted, error) in
        print("Permission granted: \(granted)")
        // 1. Check if permission granted
        guard granted else { return }
        // 2. Attempt registration for remote notifications on the main thread
        DispatchQueue.main.async {
            UIApplication.shared.registerForRemoteNotifications()
        }
    }
}

Solution

  • You need to import the related delegate (UNUserNotificationCenterDelegate) in your AppDelegate class first like below code.

    class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate
    

    In your code UNUserNotificationCenter.current().delegate = self self doesn't respond to required delegate that is why you are getting error message.