NSUserDefaults losing its keys & values when phone is rebooted but not unlocked
background, core-location, ios, nsuserdefaults, reboot
Solution
After a while, Apple recognised this as an official bug. So we are only left with different workarounds until it's solved:
If you need the data while executing BEFORE the phone has been unlocked use one of the following options and set the `NSPersistentStoreFileProtectionKey = NSFileProtectionNone` option:
- Save data using Core Data. (If you need to access the DB in background when the phone wasn't unlocked yet AND you don't have sensible information in it, you can add to the options Array the following option: `NSPersistentStoreFileProtectionKey = NSFileProtectionNone`)
- Use the Keychain.
- Use a .plist file.
- Use custom made files: (e.g.: .txt with a specific format).
- Any other way you might find comfortable for storing data.
Choose yours ;)
If you don't need or don't care about the data before the phone has been unlocked you can use this approach (Thanks @maxf):
Register to the `applicationProtectedDataDidBecomeAvailable:` notification and execute the following line of code inside the callback `[NSUserDefaults resetStandardUserDefaults]`
This will make you `NSUserDefault` reload right after your phone has been granted permission to access protected data, helping you to avoid this issue entirely.
Thanks all for the help!
Problem
We are currently experiencing the following weird issue with our iPhone app. As the title says, `NSUserDefaults` is losing our custom keys and values when phone is rebooted but not unlocked, and this is happening on a very specific scenario. Context: We are using the `NSUserDefaults` in the app to store user data (e.g. username). Our app has Location enabled on Background Mode. We are experiencing this issue only when distributing over the air or by Testflight. If I drag and drop the .ipa (same that was distributed over the air) into my phone using Xcode I don't experience this issue. Situation: The user installs the app, logs in and the username is stored on the `NSUserDefaults` successfully. Then, the user switches OFF they device and turns it back ON and lets the phone sit around for some time before unlocking the screen. Problem: If in that time a significant location change is triggered, the app comes to live on background but the `NSUserDefaults` is empty (Only has some keys from apple but none of our custom keys). Then, the `NSUserDefaults` never gets this keys recovered no matter what you do (e.g. if you unlock your phone and open the app you will see the keys are still missing). Any help or idea will be truly appreciated :)