I'm developing an iOS app with Firebase. My root view controller is a UITabBarController
.
All of the controllers within said TabBar need to listen to a User
document in Firebase's Firestore, but creating a listener in each one doesn't seem to be the most efficient way to do it.
I'm aware I could create the listener in a CustomTabBarController
like so:
import UIKit
import FirebaseFirestore
class CustomTabBarController: UITabBarController {
var userListener: ListenerRegistration?
var user: User? // User is a custom class
override func viewDidAppear(_ animated: Bool) {
let userID = UserDefaults.standard.value(forKey: "id") as! String
userListener = Firestore.firestore().document("users/\(userID)").addSnapshotListener { (document, error) in
if let document = document {
self.user = User(firebaseDocument: document)
} else {
// handle error!
}
}
}
override func viewDidDisappear(_ animated: Bool) {
if let listener = userListener {
listener.remove()
}
}
}
and then access that user
property from all ChildViewController
's like so:
class ChildViewController: UIViewController {
var user: User?
override func viewDidLoad() {
super.viewDidLoad()
let customTabBarController = tabBarController as! CustomTabBarController
self.user = customTabBarController.user
}
}
I find two problems with this approach:
- The
user
property inChildViewController
will not update, as it is only set in theviewDidLoad
method. - I don't think
CustomTabBarController
is the place to handle the listener failure. DifferentChildViewController
's will have different ways to deal with it.
Questions: What are my options to create a listener capable of updating any UIVIewController
's that need its result? Am I on the right path here or maybe I can use the AppDelegate
or even a Singleton to achieve this.
Thanks!