Sreehari
Sreehari

Reputation: 5655

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

Upvotes: 1

Views: 691

Answers (3)

Bhaumik
Bhaumik

Reputation: 1238

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

Upvotes: 4

Shehata Gamal
Shehata Gamal

Reputation: 100533

The rational is very simple if you need to monitor when the vc ( imagePicker ) is shown then implement UINavigationControllerDelegate methods so it will has a meaning otherwise it's useless , but it's mandatory

Upvotes: 0

cekisakurek
cekisakurek

Reputation: 2474

UIImagePickerController's delegate is defined as

@property(nullable,nonatomic,weak) id <UINavigationControllerDelegate, UIImagePickerControllerDelegate> delegate;

So the delegate you want to set must conform UINavigationControllerDelegate.

UINavigationControllerDelegate has no mandatory fields. So you do not need to implement any function or variable to conform that. Hence your error is solved.

Screenshot of UINavDelegate

Upvotes: 1

Related Questions