Search code examples
iosswiftxcode6uipageviewcontroller

Swipe between multiple view controllers using UIPageViewController


My UIPageViewController not working at all. What I'm trying to do is switch 2 view controllers inside UIPageViewController. I already followed guideline here but fail. Using UIPageViewController with swift and multiple view controllers. First view controller appeared successful but when I tried swipe to second view controller it throw this error message. I already set all identifiers correctly.

fatal error: unexpectedly found nil while unwrapping an Optional value

It's cause from here

func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {

        let identifier = viewController.restorationIdentifier
        let index = self.identifiers.indexOfObject(identifier!) // error message here

        //if the index is 0, return nil since we dont want a view controller before the first one
        if index == 0 {

            return nil
        }

        //decrement the index to get the viewController before the current one
        self.index = self.index - 1
        return self.viewControllerAtIndex(self.index)

    }

Main.storyboard

enter image description here

Source code: https://github.com/datomnurdin/RevivalxSwiftPageViewController


Solution

  • The crash occurs while trying to access the restorationIdentifier of your view controller. You used ! to unwrap it but it's nil ; as a first solution, set the restorationIdentifier in the storyboard.

    enter image description here

    In general, use ! to unwrap a value only if you're sure it's not nil (by adding a if statement just before).