简体   繁体   中英

How to override initial ViewController on First Run thru AppDelegate

I am using the following code to detect whether the app is running for the first time:

    // Detect First Launch

    let firstLaunch = NSUserDefaults.standardUserDefaults().boolForKey("FirstLaunch")
    if firstLaunch  {
        print("Not first launch.")
        Show()
    }
    else {
        print("First launch, setting NSUserDefault.")
        NSUserDefaults.standardUserDefaults().setBool(true, forKey: "FirstLaunch")
    }

I am using the following function to show the ViewController:

func Show(){
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewControllerWithIdentifier(“myViewController”) as! MyViewController
    self.window?.rootViewController?.presentViewController(vc, animated: true, completion: nil)
}

I put both code under: func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

However, when I build and run the app, the initial view controller is shown as if nothing happened. I want “myViewController” to be shown FIRST (during the app's FIRST EVER LAUNCH on the device.) After that first launch, however, the “myViewController” won't be shown anymore, unless the user uninstalls and freshly reinstalls the app.

Does anyone know how to do it?

Since you want to show the custom screen on first launch and then dismiss it, I would run this code in your normal root VC's viewWillAppear(animated:Bool) method

EDIT:

Yes, you will have to modify the code a bit. For example, like so:

func Show(){
    guard let sb = storyboard else { return }
    let vc = sb.instantiateViewControllerWithIdentifier(“myViewController”) as! MyViewController
    navigationController?.presentViewController(vc, animated: true, completion: nil)
}

After setting the value to user defaults, you have to save it using the synchronize method. This method is invoked periodically buy the system, but if you didn't synchronize before it was called, your value isn't saved.

NSUserDefaults.standardUserDefaults().setBool(true, forKey: "FirstLaunch")
NSUserDefaults.standardUserDefaults().synchronize()

Documentation of synchronize from to Apple docs :

Writes any modifications to the persistent domains to disk and updates all unmodified persistent domains to what is on disk.

Discussion

Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM