6

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
    }
}

1 Answer 1

15

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Do we know if this is guaranteed to be called only once, like a main method? Or is the App struct like the View structs – created repeatedly?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.