我正在使用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中做的事情?
答案 0 :(得分:8)
您可以使用AppDelegate
,
applicationState
中实现此目的
在iOS8中:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
if !UIApplication.shared.applicationState == .active {
// Handle your push notification here
}
}
在iOS10中:
import UserNotifications
框架实施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])
}
}
感谢。
答案 1 :(得分:2)
在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
}