Friday, 15 May 2020

Protocol Extension for camera and gallery picker

We can implement the gallery and camera functionality in one line using protocols power.
 The syntax of protocol is really simple.
Protocol Syntax
While working with protocol, you will get to know that there are multiple ways to declare an optional function. One way to declare optional functions is to define functions with empty body in the protocol extension. You can define body for any function to make it optional.
Optional functions for protocol

The fun part begins…

As you can see my ‘ImagePickerProtocol’ conforms a protocol ‘Au

For Authorization purpose we have separate protocol as it may be used for many other authorisations as well.
You can add all the authorization in “AuthorizationProtocol” required throughout the app.
AuthorizationProtocol
Authorization Protocol extension
I can use these authorization methods for access to open camera or gallery. So in my ‘ImagePickerProtocol’ extension, I will call these methods to check authorization and open camera or gallery as per the requirement.
Default definition of ImagePickerProtocol functions
Apart from the protocol functions you can also provide some extra properties or functions to complete your functionality. In this case, I used a computed property for UIImagePickerProtocol object and a function for alert to redirect user to “Setting” page of the application to change the access.
Private computed property
Private function
That’s it. Just conform the ImagePickerProtocol and use its functions.
Conforming Protocol
Using Protocol functions
Well this is just an example for ImagePicker, it can also be used for document picker, alerts, etc.

No comments:

Post a Comment