Reputation: 119
I am making a Firebase project that requires numerous features including authentication, database, and storage. I think that making a database reference in every view controller is too strenuous, so I am making a Firebase manager class that takes care of uploading/downloading/authenticating process.
import Foundation
import Firebase
class FirebaseManager {
var uid: String?
var databaseRootRef: DatabaseReference?
var storageRootRef: StorageReference?
var authentication: Auth?
init() {
}
func initialize() {
uid = Auth.auth().currentUser?.uid
databaseRootRef = Database.database().reference()
storageRootRef = Storage.storage().reference()
authentication = Auth.auth()
}
func isAuthenticated() -> Bool {
return authentication?.currentUser != nil
}
func registerUserWith(name: String, email: String, password: String, completionHandler: (@escaping (User?, Error?) -> Void)) {
authentication?.signIn(withEmail: email, password: password, completion: { (user, error) in
completionHandler(user, error)
})
}
}
I have two questions:
I am not even sure if this is good programming practice. I don't see many online tutorials do that. However, I personally think it is good because (a) My classes are created so that they have one unique purpose. My view controller doesn't need to worry about the firebase work (b) it makes a lot of my code reusable and saves a lot of lines (c) I just think that it allows me to edit any firebase related methods easier because now I only have to edit one place instead of 20 places
Suppose that this is good programming practice. How should I implement this class? What I am doing right now is that I create an instance in each view controller file and initialize them in each file. Alternatively, I could (a) make all the members and methods of the class static so I access them directly without initializing an object (b) don't initialize an object in each view controller but instead pass one object throughout via segue transfers. Which one is the better design method
P.S. The reason I have a separate initialize method is that if I init the object before viewDidLoad or when I define the object, the program crashes because the Firebase references haven't been created yet.
Thanks a lot!
Upvotes: 0
Views: 761
Reputation: 27221
I recommend not using static/singleton pattern.
You can use subclassing instead.
I mean, you can create, for instance, FirebaseViewController
which handles basic interaction with FirebaseManager
.
The problem while using a singleton is that you can't clearly understand when your data changing.
By the way, use computed properties instead. This is the Swift-style:
var isAuthenticated: Bool {
return authentication?.currentUser != nil
}
Upvotes: 2