当应用程序处于后台时,将Firebase侦听器保留在内存中 [英] Keep a Firebase listener in memory when the app is in background

查看:114
本文介绍了当应用程序处于后台时,将Firebase侦听器保留在内存中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用Firebase侦听器来触发本地通知。我找到了一个​​帖子,这个地址正是我正在尝试的与大部分的解释,但我没有评论的职位声誉,似乎没有迹象表明如何完成我想要的任何地方。

<原来的海报说这个。


我想明白了!我必须使用不同的方法,但是我能够
让我的Firebase数据库观察者触发
背景中的通知。



只要包含数据库观察者的对象不是
从内存释放它将继续观察和触发。所以我
创建了一个包含静态数据库对象
属性的全局类:



  class GlobalDatabaseDelegate {
static let dataBase = DataBase()
}

这是我为自己的项目而感到困惑的地方。我的理解是我必须创建一个类似于DataBase()的类,它包含我的数据库引用。问题是我不明白如何创建包含数据库监听器的类对象。



例如我的引用是:

  let userRef = FIRDatabase.database.reference()。child(users)

我想观察添加到数据库的任何用户,然后触发本地通知。我能够编写代码来完成这个工作,只是不知道如何将它包含在自己的对象类中,然后使其成为静态的。



原谅我有点慢。任何帮助将非常感激。

其余的帖子如下:


我也将DataBase类扩展为
UNUserNotificationCenterDelegate,以便它可以像这样发送推送标识符



UNIserNotificationCenterDelegate {

func userNotificationCenter(_center:UNUserNotificationCenter,didReceive响应:UNNotificationResponse,withCompletionHandler completionHandler:@escaping() - >无效)

  {
print(点击通知)
}

func userNotificationCenter(_ center:UNUserNotificationCenter,willPresent notification:UNNotification,withCompletionHandler completionHandler:@escaping(UNNotificationPresentationOptions) - > Void){
print(Notification being triggered)
completionHandler([.alert,.sound,.badge])
}

func observeNotificatio nsChildAddedBackground(){
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? [字符串:任何]
如果让newNotificationJSON = newNotificationJSON {
让状态= newNotificationJSON [状态]
如果让状态=状态为? Int {
if status == 1 {
self.sendPushNotification()
}
}
}
})
}

func sendPushNotification(){
let content = UNMutableNotificationContent()
content.title =这是一个新的通知
content.subtitle =new notification push
content.body =有人做了一些触发通知
content.sound = UNNotificationSound.default()

let request = UNNotificationRequest(identifier:\(self.notificationBackgroundProcessName ),content:content,trigger:nil)
UNITNotificationCenter.current() ).add(request){
中的错误,如果错误!= nil {
p rint(发送推送通知的错误:\(error?.localizedDescription))
}
}
}
}



实质上,我试图在应用程序处于后台时在内存中保留一个Firebase侦听器。

我也用稍微不同的方法实现了我的代码。

我发现了另一篇文章,详细介绍了运行自定义数据服务类所需的技术。 自定义Firebase数据服务类:Swift 3



要设置保持内存中的Firebase侦听器的步骤很少。

1.创建一个firebase数据服务类。在那个类中,我有一个静态变量,它是同一个类的

  class FirebaseAPI {
var isOpen = false

static let sharedInstance = FirebaseAPI()

//我在这个类中添加了firebase引用的函数

func observeNotifications(){

// firebase call here


$ b code


$ b < 2.在应用程序委托中设置通知设置。这是我的设置与原来的帖子不同的地方。

  let notificationSettings = UIUserNotificationSettings(类型:[.badge,.alert,.sound],类别:nil)
UIApplication.shared.registerUserNotificationSettings(notificationSettings)



3.在viewcontroller中创建对firebase类的引用您的选择,它在应用程序委托,但不可取。

  let sharedInstance = FirebaseAPI.sharedInstance 
$ b b

4.通话功能设置观察者

  self.sharedInstance.observeNotifications()

然后,您可以使用完成处理程序触发本地通知在firebase函数中使用函数或者关闭通知。

更新:苹果已经实现了关于已经停止这种方法的背景模式的更新从工作。目前唯一的方法是使用APNS


I have been trying to use a Firebase listener to trigger local notifications. I have found a post that addresses exactly what I am trying to do with much of it explained, however I do not have the reputation to comment on the post and there seems to be no indication of how to accomplish what I want anywhere else.

The original poster says this.

I figured it out! I had to use a different approach but i was able to get my Firebase Database observer to trigger notifications in the background.

As long as the object containting the database observer is not deallocated from memory it will continue to observe and trigger. So I created a global class which contains a static database object property like this:

class GlobalDatabaseDelegate {
static let dataBase = DataBase()
 }

This is where I am confused as to what to do for my own project. It is my understanding that I have to create a class similar to DataBase() which contains my database reference. The problem is I do not understand how to create class object that will contain the database listener.

say for example my reference is :

let userRef = FIRDatabase.database.reference().child("users")

And I want to observe any users added to the database and then trigger a local notification. I am able to write the code to do so, just not sure how to contain it in an object class of its own and then make it static.

Forgive me for being a little slow. Any help would be very much appreciated.

The rest of the post follows :

I also extended the DataBase class to be the UNUserNotificationCenterDelegate so it can send the push notitications like this:

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

In essence I am trying to keep a firebase listener in memory when the app is in background.

解决方案

So the original post that I have linked in has the answer but it is a matter of understanding it. I have also implemented my code in a slightly different approach.

I found another post detailing the technique needed to run a custom data service class. Custom Firebase Data Service Class : Swift 3

To set keep the firebase listener in memory there are few steps.

1.Create a firebase data service class. In that class I have a static variable that is of the same class

class FirebaseAPI {
    var isOpen = false

static let sharedInstance = FirebaseAPI()

//  I added functions for firebase reference in this class

func observeNotifications(){

//firebase call here
 }

}

2.Set up notification settings in app delegate. This is where my set up differs from the original post.

 let notificationSettings = UIUserNotificationSettings(types: [.badge, .alert, .sound], categories: nil)
    UIApplication.shared.registerUserNotificationSettings(notificationSettings)

3.Create a reference to the firebase class in a viewcontroller of your choice, it works in app delegate but not advisable.

let sharedInstance = FirebaseAPI.sharedInstance

4.Call functions to setup observer

self.sharedInstance.observeNotifications()

You can then trigger fire a local notification using a completion handler with the function or fire off notifications within the firebase function.

Update: Apple have implemented updates in regards to background modes which have stopped this method from working . Currently the only method is to use APNS

这篇关于当应用程序处于后台时,将Firebase侦听器保留在内存中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆