3

I would like to launch a tutorial when my SwiftUI app first launches. Where in the project should this code go and how do I launch the tutorial, which is just a SwiftUI View, when the app first launches?

I already know how to check if the app has launched before using UserDefaults. I am wanting to know how to launch the SwiftUI view and then how to launch the standard ContentView after the user completes the tutorial.

let hasLaunchedBefore = UserDefaults.standard.bool(forKey: "hasLaunchedBefore")

if hasLaunchedBefore {
     // Not first launch
     // Load ContentView here
} else {
     // Is first launch
     // Load tutorial SwiftUI view here
     UserDefaults.standard.set(true, forKey: "hasLaunchedBefore") // Set hasLaunchedBefore key to true
}

2 Answers 2

2

In your SampleApp which after SwiftUI 2.0:

import SwiftUI

@main
struct SampleApp: App {
  @AppStorage("didLaunchBefore") var didLaunchBefore: Bool = true
  let persistenceController = PersistenceController.shared

  var body: some Scene {
    WindowGroup {
      if didLaunchBefore {
        SplashView()
      } else {
        ContentView()
      }
    }
  }
}

Then add a button with action like below in SplashView:

UserDefaults.standard.set(false, forKey: "didLaunchBefore")
Sign up to request clarification or add additional context in comments.

Comments

1

Try put this in your sceneDelegate

let hasLaunchedBefore = UserDefaults.standard.bool(forKey: "hasLaunchedBefore")
let content = ContentView()
let tutorial = TutorialView()
if let windowScene = scene as? UIWindowScene {
      let window = UIWindow(windowScene: windowScene)
       if hasLaunchedBefore {
           window.rootViewController = UIHostingController(rootView: content)
       } else {
           window.rootViewController = UIHostingController(rootView: tutorial)
           UserDefaults.standard.set(true, forKey: "hasLaunchedBefore") 
       }
        self.window = window
        window.makeKeyAndVisible()
}

2 Comments

That works when it is the first launch, but if I close the app after that and reopen it, it crashes.
Nevermind, I forgot to add one of my Environment Objects back to the content view. Thanks for the help!

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.