I'm implementing my login-logic using Firebase with just Facebook as provider.
How can I save my CurrentUser
after the login in order to use personal data during the app experience later?
At the moment I'm using a singleton with an instance of User
. Something like this:
CurrentUser.swift
class CurrentUser {
static let i: CurrentUser = CurrentUser()
var cUser: User?
private init() {
}
func setCurrentUser(u: User) {
cUser = u
}
func getCurrentUser() -> User {
return cUser!
}
func clearUser() {
cUser = nil
}
func userIsLogged() -> Bool {
return cUser != nil
}
}
And I'm using that singleton this way:
LoginViewController.swift
class LoginViewController: UIViewController {
...
func createCurrentUser(authData: FAuthData) {
let u = User(uid: authData.uid, displayName: authData.providerData["displayName"] as! String, email: authData.providerData["email"] as! String)
u.wrapperFromFacebookData(authData.providerData)
ref.childByAppendingPath("users").childByAppendingPath(u.uid).setValue(u.toDict())
CurrentUser.i.setCurrentUser(u)
}
...
}
I don't think this is the best practice. Before Firebase I'm used to deal with Parse builtin user logic, that was pretty easier.
The user ID and password are stored in LS as an array of objects. For this, we will create an array, and push the objects per user, to the array. The password must be stored in the LocalStorage in encrypted form, else they can be easily extracted out.
You can use a user context, where upon login the user information is stored in localStorage and in the context api. const storeUser = ({user, token}) => { localStorage. setItem('user', JSON. stringify(user)); localStorage.
Saving data to localStorage in React is super easy: const [data, setData] = useState([]); useEffect(() => { localStorage. setItem('dataKey', JSON. stringify(data)); }, [data]);
I am facing the exact problem and this link helped a lot: http://totallyswift.com/ios-app-development-part-2/
What he did was create a singleton (currentUser) that conforms with User class.
class var currentUser: User
{
struct Static
{
static var instance: User?
}
if Static.instance == nil
{
if let load: AnyObject = NSUserDefaults.standardUserDefaults().objectForKey(kUserDataKey)
{
Static.instance = User(data: load as [String: AnyObject])
}
else
{
Static.instance = User()
}
}
return Static.instance!
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With