iosfan iosfan - 2 months ago 22
Swift Question

Why NSUserDefaults does not work with Firebase

I am using

Firebase
to Login and using
NSUserdefaults
to save
uid
so next time can log in automatically. But don't know why it doesn't work. Below is my code:

// let's say path is the route down to "users" in Firebase
@IBAction func loginPressed(sender: AnyObject) {
if let email = emailField.text where email != "", let password = passwordField.text where password != "" {
FIRAuth.auth()?.signInWithEmail(email, password: password, completion: { (user, err) in
if err != nil {
print(err)
} else {
NSUserDefaults.standardUserDefaults().setValue(user!.uid, forKey: "uid")
path.child("\(user!.uid)/category").observeSingleEventOfType(.Value, withBlock: { (snapshot) in

if let userCategory = snapshot.value as? String {
if userCategory == "seller" {
self.performSegueWithIdentifier(segueSellerVC, sender: self)
} else {
self.performSegueWithIdentifier(segueCustomerVC, sender: self)
}
}
})
}
})
}
}

Answer

Swift 3

Saving

UserDefaults.standard.set(FIRAuth.auth()!.currentUser!.uid, forKey: "uid")

UserDefaults.standard.synchronize()

Retrieving

let storagePath = UserDefaults.standard.object(forKey: "uid") as? String 

Swift 2

Saving

NSUserDefaults.standardUserDefaults().setObject(FIRAuth.auth()!.currentUser!.uid, forKey: "uid")

NSUserDefaults.standardUserDefaults().synchronize()

Retrieving

let storagePath = NSUserDefaults.standardUserDefaults().objectforKey("uid") as? String
Comments