Firebase observer during all the app life

I'm trying to create a firebase observer that remains alive during all the app life. What I want is to change a property of my tabBarController when some data change in firebase. Here's my code:

self.ref.child("mySubRef").observe(.value , with: {snapshot in

        self.tabBarController?.tabBar.items?[3].badgeValue = "!"

    })

So, I've tried creating it in the viewDidLoad of my first viewController and also in the viewDidAppear. I don't remove it since I want it to be there always. In the viewDidAppear it works only if I'm in that viewController at the moment of the change. If I want that change to happen no matter where I am (always inside the tabBar) where do I have to put that code?

Thanks for the help!

Upvotes: 2

Views: 464

Answers (2)

I have found the answer. The problem was that when I changed between viewControllers the reference to the observer was deallocated. So, to fix it, I have created a class like this:

class NotificationListener: NSObject {

let ref:FIRDatabaseReference = FIRDatabase.database().reference()
var user:User?

func setUpListener(tabBarController:UITabBarController){

    self.user = User()
    self.ref.child("users/" + self.user!.uid + "/notifications").observe(.value , with: {snapshot in

        tabBarController.tabBar.items?[3].badgeValue = "!"

    })

}

}

Now I have a property of that class in every viewController and every one has a reference to the same object. When I change between VC it will not deallocate the object because it will still be referenced.

Upvotes: 2

I think, you can use Appdelegate didFinishLaunchingWithOptions method but I'm not sure.

Like this:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    FIRApp.configure()

    FIRDatabase.database().reference().child("mySubRef").observe(.value, with: { (snapshot) in
        //I'm not sure for this part.
        UITabBarController.init().tabBar.items?[3].badgeValue = "!"
    })

    return true
}

Upvotes: 0

Related Questions