user172902
user172902

Reputation: 3581

NSUSerDefault not updating my global variable for swift

I have a signin/out function for my app. However, I relised that when I logout, something is weird with my global user variable

I have a global variable under my constants.swift

var CURRENT_USER_UID = NSUserDefaults.standardUserDefaults().valueForKey("currentUserUid") as? String

However, when I logout from the current user and log a new one in, at the end of the sign in function, I have the following print statement

print("Sign in successfully. user.uid = \(user?.uid)")
print("CURRENT_USER_UID = \(CURRENT_USER_UID))")
print("NSUserDefaults.standardUserDefaults().valueForKey(KEY_USER_UID) \(NSUserDefaults.standardUserDefaults().valueForKey(KEY_USER_UID))")

These prints out

Sign in successfully. user.uid = Optional("3P9uavuLtDQZV8ColwTseBIrY4w1")

CURRENT_USER_UID = Optional("hakV4smGyveurPhFN7g9rad4xsP2"))

NSUserDefaults.standardUserDefaults().valueForKey("currentUserUid") Optional(3P9uavuLtDQZV8ColwTseBIrY4w1)

"hakV4smGyveurPhFN7g9rad4xsP2" was the previous user's userUID. "3P9uavuLtDQZV8ColwTseBIrY4w1" is the current user's UID which I only just logged in. If working correctly, I would expect all three to be "3P9uavuLtDQZV8ColwTseBIrY4w1"

Does anyone know why my CURRENT_USER_UID does not return the same thing as NSUserDefaults.standardUserDefaults().valueForKey("currentUserUid") ??

Upvotes: 1

Views: 568

Answers (2)

Paulw11
Paulw11

Reputation: 114826

Your global variable is initialised when the app is launched, so it is given the value that NSUserDefaults.standardUserDefaults().valueForKey("currentUserUid") returns at that point. When user defaults is updated the global isn't magically re-initialised. You need to update it yourself.

The simple (but wrong) solution is to assign the uid value to CURRENT_USER_ID when you complete the login and save it to NSUserDefaults.

The right solution is not to use global variables. You should encapsulate your user state in an appropriate class and use this to login/logout/obtain the current user.

Upvotes: 0

Midhun MP
Midhun MP

Reputation: 107121

The CURRENT_USER_ID won't reflect the changes happened to the NSUserDefaults. The initially assigned value won't change, the value won't be calculated again.

For fixing the issue, Either you should assign the changed user id to CURRENT_USER_ID (When that changes), or you can write a global function which returns the user id (I prefer this approach over changing the global variable in your code):

func getCurrentUserId() -> String?
{
   return NSUserDefaults.standardUserDefaults().valueForKey("currentUserUid") as? String
}

Upvotes: 4

Related Questions