'Run code during app launch in SwiftUI 2.0

In my App struct, I have a small function that checks to see if the user has opened the app before. If not, it shows an onboarding view with a few questions. Right now, I just have a .onAppear attached to both the Onboarding and ContentView to run the function, but when you launch the app, the Onboarding view flashes for a quick second. How can I run the function during launch, so the Onboarding view doesn't flash in for a second?

Here's my App struct:

import SwiftUI

@main
struct TestApp: App {
    @State private var hasOnboarded = false
    
    var body: some Scene {
        WindowGroup {
            if hasOnboarded {
                ContentView(hasOnboarded: $hasOnboarded)
                    .onAppear(perform: checkOnboarding)
            } else {
                Onboarding(hasOnboarded: $hasOnboarded)
                    .onAppear(perform: checkOnboarding)
            }
        }
    }
    
    func checkOnboarding() {
        let defaults = UserDefaults.standard
        let onboarded = defaults.bool(forKey: "hasOnboarded")
        hasOnboarded = onboarded
    }
}


Solution 1:[1]

We can do it in init, it is called once from App.main and it is very early entry point so we can just initialise property:

@main
struct TestApp: App {
    private var hasOnboarded: Bool
    
    init() {
        let defaults = UserDefaults.standard
        hasOnboarded = defaults.bool(forKey: "hasOnboarded")
    }

    // ... other code
}

backup

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1