Press "Enter" to skip to content

NSUserDefaults Lock screen issue on Xamarin iOS

Storing app settings in NSUserDefaults is a quite common thing to do in an iOS application, one way to achieve it is by using Xamarin.Essentials, which allows you to save any preference and retrieve it later even after closing/re-opening the app.

Use case

A time ago I was working with a background service that retrieved a stored app setting value when the application was re-launched from the background. To achieve it the first thing that came to my mind was using Xamarin.Essentials: Preferences.

Understanding the issue

When the background service retrieved the stored value, it was missing. After digging into this, I found this good reference that explains NSUserDefaults (Xamarin Essentials Preferences uses NSUserDefaults) is only accessible after FIRST unlock of the device.

Solution

There are several ways to solve this issue:

  • Save data using Core Data
  • Use the Keychain
  • Use a .plist file
  • Use custom made files

I choose to use the Keychain by using Xamarin.Essentials: Secure Storage which uses the keychain to store/retrieve the information.

Conclusion

If you want to retrieve information on iOS when the app launches from the background and you run into this issue, one way to fix it is by using the Keychain instead of NSUserDefaults. If you are using Xamarin Essentials use Secure Storage instead of Preferences.

References

https://damir.me/the-mystery-of-the-disappearing-nsuserdefaults-keys/

https://stackoverflow.com/questions/20269116/nsuserdefaults-losing-its-keys-values-when-phone-is-rebooted-but-not-unlocked

https://medium.com/@bohan_66764/dont-let-nsuserdefaults-betrayed-you-ccaa41013592

Happy App Settings!