I am designing an app where when the user first opens it AND they are currently logged in, I want it to take a snapshot of their data and then instantiate a view controller based on the criteria.
In my example, if the user is a "driver" meaning the value in firebase is "true" then I want them to go to the "Driver" view controller. If the user is NOT a "driver" then I want them to go to the "User" view controller (TabBarVC). If the user is nil or not logged in, then they go to the login VC.
I have tested the code without the condition. If the user is logged in (no snapshot) then it goes to TabBarVC, if they are logged out, it goes to Login VC.
When running the app with the condition, the app crashes and says "Application windows are expected to have a root view controller at the end of application launch" which to me means it is not reading my code when using the condition from the FireBase snapshot.
Please let me know what I am doing wrong, I thought that "rootVC" would work because its a variable in the form of "var rootVC : UIViewController?"
Here is switcher.swift
import Foundation
import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
class Switcher {
static func updateRootVC() {
var rootVC : UIViewController?
let currentUser = Auth.auth().currentUser?.uid
if Auth.auth().currentUser != nil{
DataService.instance.REF_USERS.child(currentUser!).observeSingleEvent(of: .value, with: { (snapshot) in
if let userSnapshot = snapshot.children.allObjects as? [DataSnapshot] {
for user in userSnapshot {
if user.childSnapshot(forPath: "driver_profile/is_userdriver").value as? Bool == false {
rootVC = UIStoryboard(name: "Driver", bundle: nil).instantiateViewController(withIdentifier: "DriverHomeVC") as! DriverHomeVC
} else {
rootVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "TabBarVC")
return
}
}
}
})
// rootVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "TabBarVC")
// rootVC = UIStoryboard(name: "Driver", bundle: nil).instantiateViewController(withIdentifier: "DriverHomeVC") as! DriverHomeVC
}else{
rootVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LoginVC") as! LoginVC
}
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = rootVC
}
}
Here is part of AppDelegate.swift incase you need to see how this is called:
import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
import FirebaseInstanceID
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
override init() {
FirebaseApp.configure()
Database.database().isPersistenceEnabled = true
}
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
Switcher.updateRootVC()
return true
}