Search code examples
iosswiftuiimagepickercontroller

UIImagePickerController and UINavigationControllerDelegate implementation


I am trying to pick an image from gallery using UIImagePickerController.

If my view controller is not mentioning UINavigationControllerDelegate. I will be getting following error while trying to set UIImagePickerController delegate.

enter image description here

But just mentioning UINavigationControllerDelegate will resolve the compile time error. Without even implementing any extra functions.

class ViewController: UIViewController ,UITextFieldDelegate 
,UIImagePickerControllerDelegate, UINavigationControllerDelegate

If someone could explain me the rational behind the same, it would be really appreciable.

I am using

Swift 4.2

Xcode 10.1

Solution

  • screenshot of UIImagePickerController declaration From documentation you can see that UIImagePickerController inherits from UINavigationController.

    screenshot of delegate declaration Looking at delegate declaration it is clear that it requires you to confirm to both UIImagePickerControllerDelegate & UINavigationControllerDelegate

    Why does delegate requires you to confirm to both protocols?

    UIImagePickerController is a system interface. This class is intended to be used as-is and allows no visual modifications. As you can see from a screenshot below it comes with a navigation bar.

    Some of the UIImagePickerControllerDelegate methods like imagePickerControllerDidCancel(_:) requires to communicate with UINavigationController in order to receive events.

    This is why UIImagePickerController must verify that you are confirming to UINavigationControllerDelegate. Hence you are seeing the error. Also note that UINavigationControllerDelegate methods are optional so that you don't actually need to implement them and this is why it simply removes error when you mention UINavigationControllerDelegate.

    screenshot of UIIMagePickerController