我的childAdded
应用中的通知表有一个Firebase 事件监听器,我想在应用程序在后台时触发推送通知.
这是听众:
@objc func observeNotificationsChildAddedBackground() { self.notificationsBackgroundHandler = FIREBASE_REF!.child("notifications/\(Defaults.userUID!)") self.notificationsBackgroundHandler!.queryOrdered(byChild: "date").queryLimited(toLast: 99).observe(.childAdded, with: { snapshot in let newNotificationJSON = snapshot.value as? [String : Any] if let newNotificationJSON = newNotificationJSON { let status = newNotificationJSON["status"] if let status = status as? Int { if status == 1 { self.sendPushNotification() } } } }) } func sendPushNotification() { let content = UNMutableNotificationContent() content.title = "Here is a new notification" content.subtitle = "new notification push" content.body = "Someone did something which triggered a notification" content.sound = UNNotificationSound.default() let request = UNNotificationRequest(identifier: "\(self.notificationBackgroundProcessName)", content: content, trigger: nil) NotificationCenter.default.post(name: notificationBackgroundProcessName, object: nil) UNUserNotificationCenter.current().delegate = self UNUserNotificationCenter.current().add(request){ error in if error != nil { print("error sending a push notification :\(error?.localizedDescription)") } } }
当应用程序位于前台时,这非常有用.然后我在我的app delegates applicationWillResignActive
方法中添加一个背景观察器来在后台观察它:
func applicationWillResignActive(_ application: UIApplication) { NotificationCenter.default.addObserver(self, selector: #selector(MainNavViewController.observeNotificationsChildAdded), name: notificationBackgroundProcessName, object: nil) }
但是当应用程序在后台时,事件观察者不会触发.我调查了Firebase Cloud Messenger来解决这个问题并遇到这样的帖子:
是否可以直接从设备使用Firebase云消息传递(FCM)向特殊UDID发送PushNotifications?
但是我并没有尝试从一个用户向另一个用户发送推送通知,我正在尝试UNNotificationRequest
从数据库监听器中激活一个.
我还发现这篇文章:
FCM背景通知在iOS中不起作用
但是,这与我的用例不同,因为它在FIRMessaging
框架内使用.
那么,当应用程序在后台运行时,是否可以运行此数据库侦听器?如果没有,我是否可以让Firebase Cloud Messenger观察表中的更改并发送通知?