For a UIKit app based on scenes (UIScene
), is it safe to reference UserDefaults
in code that is executed from UIApplicationDelegate/application(_: didFinishLaunchingWithOptions:)
?
I've read that in iOS 15, there were undocumented scenarios involving app prewarming that would cause UserDefaults
reads to fail within a window of time after device reboots, as described at https://christianselig.com/2024/10/beware-userdefaults/
The failure mode is that an app would be released, and months later, a small fraction of users would report failures consistent with UserDefaults
reads unexpectedly returning nil
, causing a loss of data. The user experience is bad, and debugging this behavior is then challenging because of how rarely it occurs.
Apple's https://developer.apple.com/documentation/uikit/app_and_environment/responding_to_the_launch_of_your_app/about_the_app_launch_sequence#3894431 seems to suggest that prewarming only executes an app "up until, but not including when main()
calls UIApplicationMain(_:_:_:_:)
, but https://stackoverflow.com/questions/71025205/ios-15-prewarming-causing-appwilllaunch-method-when-prewarm-is-done documents that UIApplicationDelegate/application(_: didFinishLaunchingWithOptions:)
has in fact been observed executing during app prewarming in scene-based apps.
So, my question: In an app based on scenes, if I'd like to reference UserDefaults
within UIApplicationDelegate/application(_: didFinishLaunchingWithOptions:)
, when is it safe to do this?
I'm guessing the answer is one of these:
- Never.
- Only in apps that don't support scenes.
- Only in iOS 16 or later.
- Only in IOS 17 or later.
Is it guaranteed safe to reference UserDefaults
in UIWindowSceneDelegate/scene(_:willConnectTo:options:)
or later?
Is there documentation from Apple regarding this issue?
Thank you.