SwiftUI @main Accessing UserDefaults Too Early Before applicationDidFinishLaunching

I'm working on a macOS and iOS app using SwiftUI. And received bug from very few user that they are being logged out, even tho they didn't.

So i'm assuming issue is relevant to this forum post, and that the keychain data and user defaults aren't available very early on in an app's lifecycle (presumably from cold start).

There is fix available for iOS but didn't find anything relevant to isProtectedDataAvailable for macOS.

I'm accessing UserDefaults in my @main view's sub view. It seems that UserDefaults is accessed too early, before applicationDidFinishLaunching. And therefore, not getting user data on launch sometimes. This issue is very rare, i'm not able to reproduce this, but assuming this can be cause based on some form post, also because view's onAppear calls before applicationDidFinishLaunching.

Answered by Rizwana in 804128022

Okay there is isProtectedDataAvailable for macOS too.

Accepted Answer

Okay there is isProtectedDataAvailable for macOS too.

Weird that it's not handled by default. Hope i'm not missing something, and it's a bug/improvement for apple!

that the keychain data and user defaults aren't available very early on in an app's lifecycle

That’s not true, and has never been true, in the standard case where the user launches your app from the home screen.

It is possible to run into problems like this if the system launches your app in the background. If your app can run in the background, you need to think carefully about what data protection class you use for your data. For example, if you store you data with the ‘protected while locked’ class and your app is run in the background when the device is locked, you won’t be able to access your data.

Regarding user defaults specifically, there isn’t a good way to manage the data protection class of the user defaults database [1]. Thus, it’s best not to store this sort of data in user defaults. Rather, store it in the keychain or in your own file, where you have direct control over the data protection.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

[1] It’s determined by the data protection class of the underlying files. That in turn may be affected by the com.apple.developer.default-data-protection entitlement. However, using that entitlement correctly is hard. If you want an easy live, don’t set that entitlement and don’t rely on access user defaults from the background.

SwiftUI @main Accessing UserDefaults Too Early Before applicationDidFinishLaunching
 
 
Q