Home > database >  How can I let user see Window with delay in SwiftUI for macOS?
How can I let user see Window with delay in SwiftUI for macOS?

Time:11-25

I want my app in SwiftUI for macOS get shown or available to user with some sec delay like 5 sec delay, how can I do this? Just given more info, I want nothing shown to user in 5 sec, and after that Window get available to user. Also I know the use case of timer or DispatchQueue, but I have no idea how can I use them for making this delay.

    @main
struct test58App: App {
    var body: some Scene {
        WindowGroup {
            // Here, I want Window get shown to user with some delay like 5 sec delay!
            ContentView()
        }
    }
}

CodePudding user response:

This would be a possible approach:

@main
struct test2App: App {
    @State private var visible: Bool = false
    var body: some Scene {
        WindowGroup {
            Group {
                if visible {
                    ContentView()
                }
            }
            .onAppear(perform: {
                DispatchQueue.main.asyncAfter(deadline: .now()   5) {
                    visible = true
                }
            })
        }
    }
}

CodePudding user response:

Approach

  • The root view (ContentView) needs to be shown, the app can't be without the root view
  • Keep the ContentView empty till 5 seconds, then show what ever you want to show

My opinion

  • It is not a good idea to keep the root view totally empty, at least show a spinner or some text otherwise user might think the app is not responding / too slow and kill the app

Code

struct ContentView: View {
    @State private var isReady = false
    var body: some View {
        Group {
            if isReady {
                Text("Ready")
            } else {
//                Text("Not Ready")
                EmptyView()
            }
        }
        .task {
            try? await Task.sleep(nanoseconds: 5_000_000_000)
            isReady = true
        }
    }
}

CodePudding user response:

If you want to hide the whole window, this would work. But it can be, that the window is visible very shortly...

@main
struct test2App: App {
    
    init() {
        NSApplication.shared.hide(nil)
        DispatchQueue.main.asyncAfter(deadline: .now()   5) {
            NSApplication.shared.unhide(nil)
            NSApplication.shared.activate(ignoringOtherApps: true)
        }
    }
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
  • Related