无法将 'AppDelegate' 分配给 'UNUserNotificationCenterDelegate'

Cannot assign 'AppDelegate' to 'UNUserNotificationCenterDelegate'

我正在学习本教程:https://medium.com/flawless-app-stories/ios-remote-push-notifications-in-a-nutshell-d05f5ccac252

但出于某种原因,我得到了

cannot assign 'AppDelegate' to 'UNUserNotificationCenterDelegate'.

那条线是做什么的?如果我将其注释掉,其余代码将起作用,并且会提示用户是否要允许通知。

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()
        }
    }
}

您需要先在您的 AppDelegate class 中 import 相关 delegate (UNUserNotificationCenterDelegate) ,如以下代码。

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate

在您的代码中 UNUserNotificationCenter.current().delegate = self self 没有响应要求 delegate 这就是您收到错误消息的原因。

UNUserNotificationCenterDelegate 导入到您的 AppDelegate Class 中,它应该可以正常工作。