Search code examples
iosswiftlaunch-screen

Unsuccessful detection of first app launching , how should I do it?


I have an app and a walkthrough screen and I want to display the walkthrough screen if the user's open the app for first time, but I do it wrong. Should I put the code in the AppDelegate or in the ViewDidLoad inside my first screen. Here is the code I used:

  super.viewDidLoad()

    if UserDefaults.standard.bool(forKey: "isFirstLaunch") {

        UserDefaults.standard.set(true, forKey: "isFirstLaunch")
        UserDefaults.standard.synchronize()
    }
    let isFirstLaunch = UserDefaults.standard.value(forKey: "isFirstLaunch") as? Bool
    if isFirstLaunch! {

            let mainStoryboard = UIStoryboard(name: "ViewController", bundle: Bundle.main)
            let vc : ViewController = mainStoryboard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
            self.present(vc, animated: true, completion: nil)


    }

and a picture of the error:

enter image description here

Any ides how to do it?


Solution

  • The (Apple) recommended way is to register the default value (as the class UserDefaults implies).

    As soon as possible – for example in applicationWillFinishLaunching – insert

    let defaultValues = ["isFirstLaunch" : true]
    UserDefaults.standard.register(defaults: defaultValues)
    

    The earliest moment is the init method in application delegate

    override init()
    {
        let defaultValues = ["isFirstLaunch" : true]
        UserDefaults.standard.register(defaults: defaultValues)
        super.init()
    }
    

    Then simply write

    func viewDidLoad()
        super.viewDidLoad()
        let defaults = UserDefaults.standard
        if defaults.bool(forKey: "isFirstLaunch") {
            defaults.set(false, forKey: "isFirstLaunch")
            let mainStoryboard = UIStoryboard(name: "ViewController", bundle: Bundle.main)
            let vc : ViewController = mainStoryboard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
            self.present(vc, animated: true, completion: nil)
        }
    }
    

    The default value is considered until it's changed the first time.