iosswiftuigesturerecognizerswrevealviewcontrollerexc-bad-instruction

Exc_bad_instruction with SWRevealViewController


Background My app has one MainViewController with a UIButton which leads to another ViewController when pressed. In the second ViewController is a UIBarButtonItem which has a "Back" segue to the MainViewController. Everything has worked fine, until now when I programmed a slide out menu with help from SWRevealViewController and I followed this Jared Davidson tutorial https://www.youtube.com/watch?v=8EFfPT3UeWs (simple, general and easy)

Problem The slide out menu works perfectly, but now when the "Back" button in the second ViewController is pressed crashes the app due to

EXC_BAD_INSTRUCTION (code=EXC_I1386_INVOP, subcode=0x0)

from the following code in the MainViewController file, regarding the pan gesture for the slide out menu.

Code

This is my MainViewControllers code regarding my slide out menu. It works perfectly, but it inferrers with the simple "Back" segue on the second ViewController.

@IBOutlet weak var Open: UIBarButtonItem!

override func viewDidLoad() {
    super.viewDidLoad()

    Open.target = self.revealViewController()
    Open.action = Selector("revealToggle:")

self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) //THIS IS THE CODE WHERE THE ERROR ALEERT OCCURS

}

When the last line of code is deleted works the "Back" segue again, but obviously not the slide out menu.

Help Is it possible specify the pan gesture code to only the MainViewController and its slide out menu, and let the "Back" segue only show the MainViewController like before and/or "ignore" this line of code. Or is it possible in some other way to separate this two and avoid my app from crashing when the "Back" segue from the second ViewController (back to the MainViewController) is pressed?

Thanks in advance legends.


Solution

  • First you need to check Open is nil. This error may occur when UIViewController was created not properly. Try this code:

    @IBOutlet weak var Open: UIBarButtonItem?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        if Open == nil {
            assertionFailure("Open is nil")
        }
    
        if let revealViewController = revealViewController() {
            Open?.target = revealViewController
            Open?.action = "revealToggle:"
    
            view.addGestureRecognizer(revealViewController.panGestureRecognizer())
        }
    }