how can I make the uiviewcontroller visible only once during first run of the app (e.g. tutorial)?

匿名 (未验证) 提交于 2019-12-03 01:10:02

问题:

I'm creating an iOS swift app and I want to show tutorial screen when user runs the app for the very first time. Later on, with each run of the app the tutorial should be hidden and another view controller should be visible as a starting point. So far my storyboard looks like this:

It contains two screens of tutorial (1st and last) and tab bar (which is a main window of my app).

As for now, in storyboard I chose the tab bar to be an initial view controller:

And with that approach the tutorial screen is never seen. How can I show it only once on first launch app and then skip it each time user opens the app?

回答1:

In didFinishLaunchingWithOptions method of AppDelegate check for NSUserDefaults value like this way.

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {      let defaults = NSUserDefaults.standardUserDefaults()     if defaults.objectForKey("isFirstTime") == nil {          defaults.setObject("No", forKey:"isFirstTime")          defaults.synchronize()          let storyboard = UIStoryboard(name: "main", bundle: nil) //Write your storyboard name          let viewController = storyboard.instantiateViewControllerWithIdentifier("ViewController") as! ViewController          self.window.rootViewController = viewController           self.window.makeKeyAndVisible()     }     return true } 

Note: I have created the object of ViewController you need to create the object of your FirstPage tutorial screen after that assign it to the rootViewController.



回答2:

For swift 4 make these changes.

let defaults = UserDefaults.standard if defaults.object(forKey: "isFirstTime") == nil {     defaults.set("No", forKey:"isFirstTime")     defaults.synchronize()     ... } 


回答3:

Simplified Swift 4 version of this answer.

https://stackoverflow.com/a/39353299/1565913

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {      if !UserDefaults.standard.bool(forKey: "didSee") {          UserDefaults.standard.set(true, forKey: "didSee")           let storyboard = UIStoryboard(name: "Main", bundle: nil)           let viewController = storyboard.instantiateViewController(withIdentifier: "YourViewController")          self.window?.rootViewController = viewController           self.window?.makeKeyAndVisible()     }      return true } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!