iOS 当应用程序处于前台时,推送通知 willPresent 通知委托方法不会被调用

iOS push notification willPresent notification delegate method is not calling when app is in foreground

我已经在应用程序中实现了推送通知。每当推送到来时,我都会收到以下委托方法的回调。

func application(_: UIApplication,
                 didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)

我已经实现了以下委托方法以在应用程序位于前台时显示推送通知。

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                    willPresent notification: UNNotification,
                                    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
    { 
       completionHandler([.alert, .badge, .sound])
    }

不幸的是,它并不是每次都有效。无论应用程序状态如何,我都会在 didReceiveRemoteNotification 方法上收到回调。这种行为有什么特别的原因吗?我错过了什么吗?

提前致谢

我认为您必须使用带有“didReceive response”签名的 userNotificationCenter 而不是 application(didReceiveRemoteNotification userInfo:..)

// MARK: Notification handling

// If the app is in the background
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    let id = response.notification.request.identifier
    print("Received notification with ID = \(id)")

    completionHandler()
}

// If the app is in the foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let id = notification.request.identifier
    print("Received notification with ID = \(id)")

    completionHandler([.sound, .alert])
}

同时让您的 AppDelegate 成为 UNUserNotificationCenter 委托。

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        UNUserNotificationCenter.current().delegate = self
    }
.
.
.
    }