0

I make onboarding with UIPageViewController its work but when I run the App for Second time the Xib not working

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        //////OnBoarding
        let lunchbefor = UserDefaults.standard.bool(forKey: "haslunched")
        self.window = UIWindow(frame: UIScreen.main.bounds)
        let lunchstoryboard = UIStoryboard(name: "onboarding", bundle: nil)
        let mainstoryboard = UIStoryboard(name: "Main", bundle: nil)

        var vc: UIViewController
        if lunchbefor{
            window?.rootViewController = MainVC()
            vc = mainstoryboard.instantiateInitialViewController()!

        }else{
            vc = lunchstoryboard.instantiateViewController(withIdentifier: "start")
        }
        UserDefaults.standard.set(true, forKey: "haslunched")
        if lunchbefor == false{

            self.window?.rootViewController = vc
            self.window?.makeKeyAndVisible()
        }else{
            window?.makeKeyAndVisible()
            window?.rootViewController = MainVC()

        }

        return true
    }

error:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"

on this line:

vc = mainstoryboard.instantiateInitialViewController()!
Maciej Gad
  • 1,701
  • 16
  • 21

2 Answers2

0

I find the answer I did this:

  var vc: UIViewController

    if lunchbefor{
        window?.rootViewController = MainVC()
       // vc = mainstoryboard.instantiateInitialViewController()!
        vc =  MainVC()

    }else{
        vc = lunchstoryboard.instantiateViewController(withIdentifier: "start")
    }
0

If you want to use instantiateInitialViewController you need to select Is Initial View Controller in a storyboard (red arrow on the screen), and you will see an indicator that the view controller is the initial one (green arrow)

Selecting a <code>Is Initial View Controller</code>

Also, it is a good idea not to use force unwrap (!) as it will crash your app when a variable is nil.

Maciej Gad
  • 1,701
  • 16
  • 21