I started to use this solution and polished it a little bit, and I came to a pretty handy solution.
I created a custom class named FirebaseAPI. This is a singleton class. This class contains all the methods for Firebase (Authentication, Database, Storage, ...).
Example:
FirebaseAPI.swift
import FirebaseAuth
import FirebaseDatabase
class FirebaseAPI {
static let shared = FirebaseAPI()
private init() {}
//Authentication
func logInUser(onCompletion: @escaping (String?) -> Void {
FIRAuth.auth().signInAnonymously(completion: {(user, error) in
if error == nil {
onCompletion(user!.uid)
} else {
onCompletion(nil)
}
})
}
//Database
func getObjects(parameter: ParamaterClass, onCompletion: @escaping ([ObjectClass]) -> Void) {
Constants.Firebase.References.Object?.observe(.value, with: { snapshot in
var objects = [ObjectClass]()
if snapshot.exists() {
for child in snapshot.children.allObjects {
let object = Object(snapshot: child as! FIRDataSnapshot)
objects.append(object)
}
}
onCompletion(objects)
})
}
}
Constants.swift
import FirebaseDatabase
struct Constants {
struct Firebase {
static var CurrentUser: FIRDatabaseReference?
static var Objects: FIRDatabaseReference?
}
}
AppDelegate.swift
import UIKit
import Firebase
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FIRApp.configure()
FirebaseAPI.shared.logInUser(onCompletion { uid in
if uid != nil {
Constants.Firebase.References.CurrentUser = FIRDatabase.database().reference().child("users").child(uid!)
Constants.Firebase.References.CurrentUser.keepSynced(true)
Constants.Firebase.References.Objects = FIRDatabase.database().reference().child("objects")
Constants.Firebase.Reference.Objects?.keepSynced(true)
}
})
}
return true
}
I can give you a example of calling methods in the FirebaseAPI in a ViewController, but an example of such a method is given in the code of the AppDelegate.swift up here (the FirebaseAPI.shared.logInUser method).
Used this structure in 3 different projects up till now and it works fluently!