0

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?

Sente
  • 277
  • 4
  • 11
  • Instead of trying to keep the listeners connected, why not use Cloud Functions for Firebase with FCM? Here's some documentation if you're interested in finding out more: https://firebase.google.com/docs/functions/, https://firebase.google.com/docs/cloud-messaging/ – Jen Person Sep 15 '17 at 22:42
  • because...lack of knowledge lol and I don't really like Firebase to begin with – Sente Sep 15 '17 at 22:54

0 Answers0