您可以发送将在前台和后台接收的数据通知。在 iOS 中,它们由委托方法 application(_:didReceiveRemoteNotification:fetchCompletionHandler:) 处理,处理后您可以决定是否为用户创建推送。
@update
用于在低于 10 的 iOS 上接收数据消息(不推送)
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
handleNotification(data: userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
在 iOS10 上
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
handleNotification(data: remoteMessage.appData)
}
然后我只检查自定义字段是否有我需要的数据并使用 NotificationCenter 创建本地通知
fileprivate func handleNotification(data: [AnyHashable : Any]) {
guard let topic = data["topic"] as? String else { return }
if data["receiver"] as? String == UserManager.shared.current(Profile.self)?.uuid && topic == "coupons" {
displayNotification(data: data)
}
}
fileprivate func displayNotification(data: [AnyHashable : Any]) {
if #available(iOS 10.0, *) {
let content = UNMutableNotificationContent()
content.title = data["notification_title"] as! String
content.body = data["notification_body"] as! String
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 1, repeats: false)
let request = UNNotificationRequest.init(identifier: data["topic"] as! String, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)
} else {
if currentNotification != nil {
UIApplication.shared.cancelLocalNotification(currentNotification!)
}
let notification = UILocalNotification()
notification.fireDate = Date()
notification.category = data["topic"] as? String
notification.alertBody = data["notification_body"] as? String
if #available(iOS 8.2, *) {
notification.alertTitle = data["notification_title"] as? String
}
currentNotification = notification
UIApplication.shared.scheduleLocalNotification(currentNotification!)
}
}
请记住,这适用于数据通知而不是推送通知,但在 Firebase 中您可以发送这两种类型。