Best practices for storing CurrentUser after login

I use my login logic using Firebase using only Facebook as a provider.

How can I save my CurrentUser after logging in to use my personal data while using the application later?

I am currently using singleton with a User instance. Something like that:

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 use this singleton as follows:

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 do not think this is the best practice. Before Firebase, I used to deal with Parse user logic, which was pretty easy.

+5
source share
1 answer

I ran into the exact problem and this link really helped: http://totallyswift.com/ios-app-development-part-2/

What he did was create a singleton (currentUser) that corresponds to the 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! } 
+1
source

Source: https://habr.com/ru/post/1242565/


All Articles