-1

I have a very weird problem in Swift3. I want to keep an user logged into application after he has already authenticated in his last session.

My problem is that UserDefaults return sometimes true, sometimes false even if is logged in his account. The problem makes me crazy. I use an bool value stored in UserDefaults, I tried to save a specific string but the problem persist.

Anyone had this problem? Any solutions?

Here is the code when I log in:

UserDefaults.standard.set(true, forKey: LOGIN)

And this is my code in AppDelegate in didFinishLaunchingWithOptions method:

if UserDefaults.standard.bool(forKey: LOGIN) {
    AppData().updateUserInformation()
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Gaby Fitcal
  • 1,814
  • 1
  • 17
  • 28

1 Answers1

1

I suggest calling UserDefaults.standard.synchronize() after setting UserDefaults values. A lot of developers say that you don't need to do this and that iOS will take care of it for you.

But I've found that not always to be the case, especially when reading values shortly after setting them, or if the app exits before they are synchronized and therefore are lost.

picciano
  • 22,341
  • 9
  • 69
  • 82
  • 1
    UserDefaults is nothing but an in-memory dictionary backed up to a plist on occasion. There is no way that a value set in user defaults can't be read back immediately, with or without synchronizing. Please see http://stackoverflow.com/a/40809748/1226963 for complete details. – rmaddy Feb 23 '17 at 16:58
  • All I'm saying is that practical experience has shown otherwise. Accessing UserDefaults.standard from different threads exacerbates the situation. – picciano Feb 24 '17 at 02:37