I have a chat feature that utilizes a firebase listener that fires when a "new message" is made in order to launch a notification. The problem is that the listener object gets deallocated from memory so there will be no notifications. After researching I have found that I need to use a data service class to hold the listener object to keep it in memory.
Keep a Firebase listener in memory when the app is in background
I am using MySQL to hold the chat IDS and doing an http request to fetch them in ViewDidAppear. Then I am looping through the array of IDs to attach the listeners like so:
for value in informationArray {
let chatRef = DatabaseReference.chats.reference()
let query = chatRef.queryOrdered(byChild: "uid").queryEqual(toValue: (value))
query.observe(.childAdded, with: { snapshot in
let chat = Chat(dictionary: snapshot.value as! [String : Any])
if !self.chats.contains(chat) {
self.chats.insert(chat, at: 0)
self.tableView.reloadData()
//self.fetchChats()
}
chat.ref.child("lastMessage").observe(.value, with: { snapshot in
//(some code that performs tasks specific to this view controller)
let content = UNMutableNotificationContent()
content.title = "You have a new Message!"
content.subtitle = chatTitle
content.body = chat.lastMessage
content.badge = 1
let trigger = UNTimeIntervalNotificationTrigger (timeInterval: 1, repeats: false)
let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
})
chat.ref.child("lastUpdate").observe(.value, with: { snapshot in
//(some more code that performs tasks specific to this view controller)
I need to keep the reference for "lastMessage" turned on so I will continue to get the notifications. I also need this reference to perform the additional VC tasks. Finally, I have to keep the additional references (chat.ref.child...) though they can be deallocated. How can I setup my data service class to accomplish my goals?