在前台时不显示通知

我正在使用Firebase管理SDK从我的节点服务器发送推送通知。 但是在iOS上我只想在应用程序处于后台/终止时显示通知,而不是在前台时显示。 目前它将始终显示通知。

这是我的有效载荷:

const payload = { data: { data: 'data', more: 'moreData', }, notification: { title: 'Incoming Call', body: 'Someone is calling you', text: 'This is some text', sound: 'default', click_action: 'com.example.INCOMING_CALL', } }; const options = { priority: 'high', time_to_live: 30, collapse_key: 'Video Call', content_available: true, }; admin.messaging().sendToDevice(tokensList, payload, options); 

它是我的有效载荷的东西还是我必须在AppDelegate.swift中做的事情?

您可以使用applicationStateAppDelegate实现此目的,

在iOS8中:

  func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) { if !UIApplication.shared.applicationState == .active { // Handle your push notification here } } 

在iOS10中:

  1. import UserNotifications框架
  2. 实现UNUserNotificationCenterDelegate方法

     func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { if UIApplication.shared.applicationState == .active { // In iOS 10 if app is in foreground do nothing. completionHandler([]) } else { // If app is not active you can show banner, sound and badge. completionHandler([.alert, .badge, .sound]) } } 

谢谢。

在iOS中,您决定使用AppDelegate.swift,如何处理通知。 在AppDelegate中处理适当案例的通知,并在应用程序处于前台时丢弃。

在iOS 10中,要在应用程序终止时处理通知并从通知启动应用程序,请将其处理

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { if launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] != nil { if let remoteNotif = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary } } } 

要处理前台通知,请使用此方法

  func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { //handle notification here } 

要处理后台通知,请使用以下方法:

  func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { //handle notification here }