When the user logs in, I am retrieving their data from Firebase and storing it in a struct in my LogInViewController
. So to retrieve it from any ViewController, I just simply have to call LogInViewController.myVariables.person?.getFirstName()
to get their first name and etc. But doesn't this create a memory usage issue because I am instantiating LogInViewController
every time I call it? What is the best practice for storing user data to be used throughout all the ViewControllers?
This is what a function in my SceneDelegate looks like.
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if KeychainWrapper.standard.string(forKey: "email") != nil && KeychainWrapper.standard.string(forKey: "password") != nil { //if the keychain isn't nil, then sign-in
print("here keychainwrapper is not nil")
Auth.auth().signIn(withEmail: KeychainWrapper.standard.string(forKey: "email")!, password: KeychainWrapper.standard.string(forKey: "password")!) { (result, error) in
if error == nil {
if Auth.auth().currentUser!.isEmailVerified {
self.getData(result!, completionHandler: { () in
//gets data, then goes to TabBarController
window.setRootViewController(storyboard.instantiateViewController(withIdentifier: "TabBarController"), options: UIWindow.TransitionOptions(direction: .fade))
self.window = window
window.makeKeyAndVisible()
})
}else{ //if they aren't verified
window.setRootViewController(storyboard.instantiateViewController(withIdentifier: "ViewController"), options: UIWindow.TransitionOptions(direction: .fade))
self.window = window
window.makeKeyAndVisible()
}
}else{ //if there is a sign-in error window.setRootViewController(storyboard.instantiateViewController(withIdentifier: "ViewController"), options: UIWindow.TransitionOptions(direction: .fade))
self.window = window
window.makeKeyAndVisible()
}
}
}else{ //if keychain is nil
window.setRootViewController(storyboard.instantiateViewController(withIdentifier: "ViewController"), options: UIWindow.TransitionOptions(direction: .fade))
self.window = window
window.makeKeyAndVisible()
}
//guard let _ = (scene as? UIWindowScene) else { return }
}
}
func getData(_ result:AuthDataResult, completionHandler: @escaping() -> Void){
let user = result.user
let docRef = db.collection("Users").document(user.uid)
docRef.getDocument { (document, error) in
if document != nil && document!.exists {
let d = document!.data()
LogInViewController.myVariables.person = Person(d!["firstName"]! as! String, d!["lastName"]! as! String)
completionHandler()
}
}
}