Show tutorial view controller ONCE in swift

880 Views Asked by At

I am fairly new to programming and am struggling with being able to programmatically show a "tutorial" view controller only once when the users open the app.

I have referenced previous questions here to get code but it does not seem to work on my app. From these pictures below, you can see the setup of my storyboard and my didFinishLaunchingWithOptions function code.

ALSO, I tried programmatically loading my tutorial view controller every time I launch the app (so I removed the user defaults code) and that does not work either. When I did this, I simply get a black screen.

Am I missing something in my code or is there a setting I am missing to check? I am using Xcode Ver 11.5 and swift 5.

code used:

var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    
    
    window = UIWindow(frame: UIScreen.main.bounds)
    let defaults = UserDefaults.standard
    if defaults.object(forKey: "FirstTime") == nil {
        defaults.set("No", forKey:"FirstTime")
        defaults.synchronize()
        
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        
        let viewController = storyboard.instantiateViewController(withIdentifier: "TutorialViewController") as! TutorialViewController
        
        window?.rootViewController = viewController
        window?.makeKeyAndVisible()
    }
    
    
    
    
    
    
    
    
    
    

storyboard

appDelegateCode

1

There are 1 best solutions below

2
On BEST ANSWER

Not quite sure if this is what you want.

     if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        
        let defaults = UserDefaults.standard
        if defaults.object(forKey: "FirstTime") == nil {
            defaults.set("No", forKey:"FirstTime")
            window.rootViewController = TutorialViewController()
        } else {
            window.rootViewController = OtherViewController()
        }
        self.window = window
        window.makeKeyAndVisible()
    }