gpt4 book ai didi

ios - 应用程序在后台时的 Firebase 监听器

转载 作者:搜寻专家 更新时间:2023-10-30 23:05:40 26 4
gpt4 key购买 nike

我的应用程序中的通知表有一个 Firebase childAdded 事件监听器,我想在应用程序处于后台时触发推送通知。

这是监听器:

@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)")
}
}
}

当应用程序位于前台时,这非常有用。然后我在我的应用程序委托(delegate) applicationWillResignActive 方法中添加一个后台观察器以在后台观察它:

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

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

Is it possible to send PushNotifications, using Firebase Cloud Messaging (FCM) to special UDID, directly from device?

但是我并没有尝试将推送通知从一个用户发送到另一个用户,我正在尝试从数据库监听器中激活 UNNotificationRequest

我还找到了这篇文章: FCM background notifications not working in iOS但同样,这与我的用例不同,因为它是在 FIRMessaging 框架中使用的。

那么,是否可以在应用程序处于后台时运行此数据库监听器?如果没有,我是否可以让 Firebase Cloud Messenger 观察表格中的变化并发送通知?

最佳答案

我遇到了同样的问题,几个月前看到了你的帖子。我终于明白了在后台观察通知需要什么。

我在这篇文章 https://stackoverflow.com/a/42240984/7048719 中详细介绍了我正在使用的解决方案

技术如下

  1. 使用自定义数据服务类
  2. 初始化数据服务类的共享实例
  3. 在数据服务类中调用适当的函数来自初始 View Controller 的 sharedInstance。

这样观察者就留在内存中

更新:Apple 已经实现了有关后台模式的更新,阻止了此方法的工作。

关于ios - 应用程序在后台时的 Firebase 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41685353/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com