【发布时间】:2017-06-27 00:27:26
【问题描述】:
我一直在尝试使用 Firebase 侦听器来触发本地通知。我找到了一个post,它准确地解决了我试图解释的大部分内容,但是我没有对帖子发表评论的声誉,而且似乎没有迹象表明如何在其他任何地方完成我想要的.
原海报是这么说的。
我想通了!我不得不使用不同的方法,但我能够 让我的 Firebase 数据库观察者在 背景。
只要包含数据库观察者的对象不是 从内存中释放,它将继续观察和触发。所以我 创建了一个包含静态数据库对象的全局类 像这样的属性:
class GlobalDatabaseDelegate {
static let dataBase = DataBase()
}
这是我对如何为自己的项目做什么感到困惑的地方。据我了解,我必须创建一个类似于 DataBase() 的类,其中包含我的数据库引用。问题是我不明白如何创建将包含数据库侦听器的类对象。
比如说我的参考是:
let userRef = FIRDatabase.database.reference().child("users")
我想观察添加到数据库中的任何用户,然后触发本地通知。我可以编写代码来执行此操作,只是不确定如何将其包含在自己的对象类中,然后使其成为静态。
原谅我有点慢。任何帮助将不胜感激。
帖子的其余部分如下:
我还将 DataBase 类扩展为 UNUserNotificationCenterDelegate 以便它可以发送推送通知 像这样:
extension DataBase: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("Tapped in notification")
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
print("Notification being triggered")
completionHandler( [.alert,.sound,.badge])
}
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)")
}
}
}
}
本质上,当应用程序处于后台时,我试图将 firebase 侦听器保留在内存中。
【问题讨论】:
标签: ios swift firebase firebase-realtime-database