Edward Hung Edward Hung - 1 year ago 106
Swift Question

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("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") ??

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download