当应用在后台时的Firebase监听器

人气:843 发布:2022-09-21 标签: ios firebase swift firebase-cloud-messaging unnotificationrequest

问题描述

我的应用程序中的通知表的Firebase childAdded 事件侦听器,我希望在应用程序处于后台时触发推送通知。

以下是监听器: $ b $ p $ b $ 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 newNotificationJSON = newNotificationJSON { let status = newNotificationJSON [status ] 如果让status = status为?Int { if status == 1 { self.sendPushNotification()} } } func sendPushNotification(){ let content = UNMutableNotificationContent() content.title =这是一个新的通知 content.subtitle =新通知推送 content.body =有人做了一些触发通知 content.sound = UNNotificationSound.default() $ b $ let request = UNNotificationRequest(identifier:\(self.notificationBackgroundProcessName) ,content:content,trigger:nil) NotificationCenter.default.post(name:notificationBackgroundProcessName,object:nil) UNUserNotificationCenter.current()。delegate = self UNUserNotificationCenter.current()。如果错误!= nil { print(发送推送通知错误:\(error?.localizedDescription))} } $ / code $ / pre $ b $ p

当应用处于前台时,然后,在我的应用程序委托 applicationWillResignActive 方法中添加一个背景观察器,以便在后台观察它:

  func applicationWillResignActive(_ application:UIApplication){ NotificationCenter.default.addObserver(self,selector:#selector(MainNavViewController.observeNotificationsChildAdded),name:notificationBackgroundProcessName,object:nil)}   

但是当应用程序在后台时事件观察者不会触发。我查看了Firebase Cloud Messenger来解决这个问题,并遇到类似这样的帖子:

211