如何在不点击横幅或显示通知之前访问推送通知响应?

how to access push notification response without tapping on banner or before showing notification?

我以这种方式在我的应用程序中实现了推送通知

//MARK:- Register notifications

func registerForPushNotifications() {

    if #available(iOS 10.0, *){

        let center = UNUserNotificationCenter.current()
        center.delegate = self
        center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
            if (granted)
            {
                UIApplication.shared.registerForRemoteNotifications()
            }
            else{
                //Do stuff if unsuccessful...
            }
            // Enable or disable features based on authorization.
        }
    }

    else
    {
        //If user is not on iOS 10 use the old methods we've been using
        let types: UIUserNotificationType = [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound]
        let settings: UIUserNotificationSettings = UIUserNotificationSettings( types: types, categories: nil )
        UIApplication.shared.registerUserNotificationSettings( settings )
        UIApplication.shared.registerForRemoteNotifications()

    }

}

//MARK: Push Notifications Delegate Methods

func application( _ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data ) {

    var token = ""

    for i in 0..<deviceToken.count {
        //token += String(format: "%02.2hhx", arguments: [chars[i]])
        token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])
    }

    USER_DEFAULTS.setValue(token, forKey: "Device_ID")

    USER_DEFAULTS.synchronize()

}

func application( _ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error ) {
    print( error.localizedDescription )

}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {

    UIApplication.shared.applicationIconBadgeNumber = 0

    alertRemoteNotification(userInfo as NSDictionary)
}

//Code for showing alert when in foreground

func alertRemoteNotification(_ userInfo : NSDictionary)
{
    if UIApplication.shared.applicationState == .active {

        if let aps = userInfo as? NSDictionary {

            if let apsDidt = aps.value(forKey: "aps") as? NSDictionary {

                if let alertDict = apsDidt.value(forKey: "alert") as? NSDictionary {

                    if let notification_type = alertDict.value(forKey: "name") as? String {

                        if let notification_Message = alertDict.value(forKey: "body") as? String {

                            let alert = UIAlertController(title: notification_type.capitalized + " Alert", message: notification_Message, preferredStyle: UIAlertControllerStyle.alert)
                            let okayBtn = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in

                                // When Okay

                            UIApplication.shared.applicationIconBadgeNumber = 0

                                if #available(iOS 10.0, *) {

                                    let center = UNUserNotificationCenter.current()
                                    center.removeAllDeliveredNotifications() // To remove all delivered notifications
                                    center.removeAllPendingNotificationRequests()
                                } else {
                                    // Fallback on earlier versions
                                    UIApplication.shared.cancelAllLocalNotifications()
                                }

                                let rootViewController = self.window!.rootViewController as! UINavigationController
                                let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
                                let dashBoardVC = mainStoryboard.instantiateViewController(withIdentifier: "DashBoardVC") as! DashBoardVC
                                rootViewController.pushViewController(dashBoardVC, animated: false)                                    
                            })
                            let cancelBtn = UIAlertAction(title: "Cancel", style: .default, handler: { (action) -> Void in

                                UIApplication.shared.applicationIconBadgeNumber = 0

                                if #available(iOS 10.0, *) {

                                    let center = UNUserNotificationCenter.current()
                                    center.removeAllDeliveredNotifications() // To remove all delivered notifications
                                    center.removeAllPendingNotificationRequests()
                                } else {
                                    // Fallback on earlier versions
                                    UIApplication.shared.cancelAllLocalNotifications()
                                }
                            })
                            alert.addAction(okayBtn)
                            alert.addAction(cancelBtn)

                            self.window?.rootViewController!.present(alert, animated: true, completion: nil)
                        }
                    }
                }
            }
        }
    }
    else {

        let rootViewController = self.window!.rootViewController as! UINavigationController
        let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let dashBoardVC = mainStoryboard.instantiateViewController(withIdentifier: "DashBoardVC") as! DashBoardVC
        rootViewController.pushViewController(dashBoardVC, animated: false)
    }
}

//Delegate methods

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

    completionHandler([.sound, .alert, .badge])

    UIApplication.shared.applicationIconBadgeNumber = 0

}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

    let userInfo = response.notification.request.content.userInfo as NSDictionary

    completionHandler()

    self.alertRemoteNotification(userInfo as NSDictionary)
}

我可以在点击通知横幅后访问响应,但实际问题是当我在前台时,我需要在不点击通知横幅的情况下显示带有通知响应的警报。请告诉我如何在不点击通知横幅的情况下获得回复。

创建通知服务扩展来处理通知数据。您将有 30 秒的时间通过通知服务扩展处理推送通知

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
    if let copy = request.content.mutableCopy() as? UNMutableNotificationContent {
        // Process your notification here

        contentHandler(copy)
    }
}

希望对您有所帮助

iOS 10+ 提供委托 userNotificationCenter:willPresentNotification:withCompletionHandler

Asks the delegate how to handle a notification that arrived while the app was running in the foreground.

只有在应用程序打开时才会调用。

也可以使用CONTENT-AVAILABLE=1作为触发方式。

FLOW:(没有点击通知,content-available:1

应用打开状态:- willPresentNotification(ios10+) -> didReceiveRemoteNotification:fetchCompletionHandler

后台应用程序:- didReceiveRemoteNotification:fetchCompletionHandler

App Closed:- 你不会得到通知数据,除非通过点击 Notification

打开应用

替代方法:使用富通知

您可以使用通知扩展来创建自定义推送通知(内容包括 images/videos)。 Notification Service Extension & Notification Content Extension 用于实现此目的。 mutable-content:1 需要触发它。在这里你可以下载图片,获取数据等。[但是数据只能通过UserDefaults(App Groups)与App共享,如果我错了请纠正我]

您可以 search 获取一些随机教程

@available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        completionHandler([.sound, .alert, .badge])

        UIApplication.shared.applicationIconBadgeNumber = 0

        // Added This line
        alertRemoteNotification(notification.request.content.userInfo as NSDictionary) 
    }

工作没有任何问题。