giacavicchioli February 2016

Best practice to store CurrentUser after login

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.

Answers


Ziad Alame February 2016

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!
}

Post Status

Asked in February 2016
Viewed 1,244 times
Voted 5
Answered 1 times

Search




Leave an answer