3

I have a two view controllers, ViewControllerA and ViewControllerB, embedded in a UINavigationController. ViewControllerA has a UICollectionView that displays images.

When the camera icon located at index 0 and the UICollectionViewCell is selected, it should dismiss ViewControllerA and display ViewControllerB. And also, there is a ViewController that presents ViewControllerA modally

This is what I've done, but it only dismiss ViewControllerA and nothing happens

let controller = self.storyboard?.instantiateViewControllerWithIdentifier("cameraViewController") as! UINavigationController
        self.dismissViewControllerAnimated(true, completion: { () -> Void in
            self.presentingViewController?.presentViewController(controller, animated: true, completion: nil)
        })
  • Is `presentingViewController` nil? – Jojodmo Jan 02 '16 at 21:00
  • It's not throwing any error. I debugged it by adding a breakPoint. It ran the code just didn't react to it –  Jan 02 '16 at 21:01
  • http://stackoverflow.com/questions/19857274/uinavigationcontroller-presenting-view-controller-while-dismissing-another-cont?rq=1 – Rahul Patel Jan 02 '16 at 21:01
  • It wouldn't throw an error if it was nil, because you're using `self.presentingViewController?` instead of `self.presentingViewController!`, if it is nil, that is most likely the cause of the problem - try printing `self.presentingViewController` and see what the result is. – Jojodmo Jan 02 '16 at 21:03

2 Answers2

2

When view controller is dismissed, my guess is self is already deallocated so self.presentingViewController? becomes nil too. I would create a strong reference to presenting view controller right before dismissing action takes place:

let presentingViewController = self.presentingViewController
self.dismissViewControllerAnimated(true) { completed in
  if completed {
    presentingViewController?.presentViewController(controller, animated: true, completion: nil)
  }
}

Also, make sure self.presentingViewController is not nil in the first place.

Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
  • Saw this somewhere. But, overlooked it that it'll be the cause of the problem. Thanks. –  Jan 02 '16 at 21:18
0

The reason nothing is happening is because self.presentingViewController? is nil.

If instead, you were using self.presentingViewController!, there would be an error stating Unexpectedly found nil while unwrapping optional value, which should always be avoided.

You are correct in using self.presentingViewController? instead of self.presentingViewController!, as it is much safer, but in order to fix this, you must make sure that self.presentingViewController? is not nil.

let presenting = self.presentingViewController

self.dismissViewControllerAnimated(true, completion: {() -> Void in
    presenting?.presentViewController(controller, animated: true, completion: nil)
})
Jojodmo
  • 23,357
  • 13
  • 65
  • 107