RPatel99 RPatel99 - 1 year ago 29
iOS Question

How should I configure my app to persist Firebase user data across classes?

So in my app, I have a view controller that allows the user to input an email and password into

UITextField
s, and then I log the user in with Firebase and identify their uid associated with the email. I also have a struct called
User
which contains username and userID Strings and an array of Strings (I'm not providing the code for it because I don't think it is necessary, but if you need it, let me know).

I have a class level variable

var currentUser:User? = nil


and in the login button's
@IBaction
method I do the following to initialize a user with a
FIRDataSnapshot
using the aforementioned uid:

FIRAuth.auth()?.signIn(withEmail: usernameTextBox.text!, password: passwordTextBox.text!) { (user, error) in
if error == nil {
//Valid Email and Password
let userID = FIRAuth.auth()?.currentUser?.uid

self.childRef.observe(.value, with: { snapshot in
for item in snapshot.children.allObjects as! [FIRDataSnapshot] {
let dict = item.value as! Dictionary<String,Any>
if (dict["UserID"] as? String == userID) {
self.currentUser = User(snapshot: item) //<----This is where currentUser is assigned the new User
}
//currentUser = User(snapshot: )
self.performSegue(withIdentifier: "LoginSegue", sender: sender)
}
})

}
else {
//Error stuff
}
}


My problem is that in another classes I need to access the currentUser variable (to add friends, etc.) but I am not sure how to go about it. I also cannot pull the user data from Firebase in other classes because only the one described above has access to the UserID that I need to identify which user information to use and modify.

I cannot use
prepareForSegue
because there is an SWRevealViewController in between the one where you login and the other view controllers, and SWRevealViewController is written in Objective-C, which I am not familiar with. My research has revealed that some possibilities may be global variables and singletons, but using either is seen as unsafe practice by many programmers. Also using
NSUserDefaults
(I think they've been renamed to
UserDefaults
in Swift 3) is another potential solution? I am open to any suggestions.

Thanks in advance.

Answer Source

You can do this in any view. if let currentUser =

FIRAuth.auth()?.currentUser { 
let email = currentUser.email // 
get more user data 
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download