Don't show notification when in foreground

前端 未结 2 866
走了就别回头了
走了就别回头了 2021-01-14 19:08

I\'m sending push notification from my node server using the Firebase admin SDK. But on iOS I only want to show the notification when the app is in the background/terminated

2条回答
  •  粉色の甜心
    2021-01-14 19:12

    You can achieve this in AppDelegate by using the applicationState,

    In iOS8:

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

    In iOS10:

    1. import UserNotifications framework
    2. Implement UNUserNotificationCenterDelegate method

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

    Thanks.

提交回复
热议问题