Run code during app launch in SwiftUI 2.0

拈花ヽ惹草 提交于 2020-12-26 08:47:14

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!