Ivan Ivan - 10 months ago 46
Swift Question

How to set a walkthrough/introduction screen?

I am new developer and I am struggling with my Walkthrough screen for my application.
I have created it, but when I click continue to my main screen, the app crashes.
Here is the code I have under my "continue" button:

@IBAction func skipButtonTapped(_ sender: AnyObject) {

let nextView: FirstViewController = self.storyboard?.instantiateViewController(withIdentifier: "FirstViewController") as! FirstViewController

let appdelegate = UIApplication.shared.delegate as! AppDelegate

appdelegate.window!.rootViewController = nextView


and the error I get is :

Could not cast value of type 'UITabBarController' (0x19f33c0d8) to 'Iwin.FirstViewController' (0x100057220).

I think the Problem is in the name of the name of the identifier which in my case is "FirstViewController"

This is the storyboard ID of my TabBarController, which should be the first screen of my app.

Attached I have uploaded a picture too.

Answer Source

The error you are seeing probably has to do with the forced conversion (as!) you do on the first line of the function. You're doing the following:

  1. Calling instantiateViewController(withIdentifier:), which Apple API Documentation says returns UIViewController (in this case, it's returning UITabBarController, a subclass)
  2. Force converting a UITabBarController to a FirstViewController, which fails.

This is because forced conversion guarantees that the resulting value won't be nil, but it doesn't guarantee that it won't fail (crash). UITabBarController is simply not convertible, because it does not extend/implement FirstViewController.

My guess is that even though you've given that view controller the identifier "FirstViewController", but it's just a regular old UITabBarController. Double check in Interface Builder that this View Controller is actually an instance of your FirstViewController class.

Looking at your photo, the "Class" field has the default value of UITabBarController -- this should be the first thing you try to change. Fill in FirstViewController, and let me know if it works.