问题
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:
You can do it in init, it is very early entry point so you can just initialise property:
@main
struct TestApp: App {
private var hasOnboarded: Bool
init() {
let defaults = UserDefaults.standard
hasOnboarded = defaults.bool(forKey: "hasOnboarded")
}
// ... other code
}
来源:https://stackoverflow.com/questions/63525895/run-code-during-app-launch-in-swiftui-2-0