【问题标题】:iOS push notification willPresent notification delegate method is not calling when app is in foreground当应用程序处于前台时,iOS 推送通知 willPresent 通知委托方法未调用
【发布时间】:2021-07-23 12:19:56
【问题描述】:

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

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 方法的回调。这种行为有什么特别的原因吗?我错过了什么吗?

提前致谢

【问题讨论】:

    标签: ios swift apple-push-notifications


    【解决方案1】:

    我认为您必须使用带有“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
        }
    .
    .
    .
        }
    

    【讨论】:

    • 谢谢。我对设置委托进行了仔细检查,发现它没有按预期设置。但这仍然让我感到困惑,为什么即使未设置委托,我也会在 didReceiveRemoteNotification 方法上收到回调。因此,我完全忽略了委托检查。无论如何,非常感谢。
    猜你喜欢
    • 2018-07-04
    • 2018-08-03
    • 2021-04-19
    • 2019-10-15
    • 1970-01-01
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 2017-05-27
    相关资源
    最近更新 更多