This time we will take a look on how to take photos and browse them on iOS.
Creating user interface for taking photos consists of presenting an instance of UIImagePickerController. Controller needs a delegate and source type what defines if we are going to take a photo or pick a photo from the library. But even before creating the controller it is required to call
isSourceTypeAvailable(_:) class method and verifying if the source type is available. For example, it returns false if picker’s sourceType is set to
UIImagePickerController.SourceType.photoLibrary and the library is empty. Makes sense, as there are no photos to pick from.
UIImagePickerControllerDelegate contains two methods we need to implement for handling interactions in image picker. Firstly, consuming taken or picked images and secondly, dismissing the picker. Info dictionary in
imagePickerController(_:didFinishPickingMediaWithInfo:) contains quite a many values from images to metadata. All the possible keys can be seen here. As a bare minimum we need to handle
originalImage keys. If it is required to add the image to photo library, then this can be done by calling
UIImageWriteToSavedPhotosAlbum(). This starts an asynchronous operation for adding the image to library. And if needed, it is possible to specify callback when this operation finishes.
Before going ahead and presenting the image picker it is required to add privacy statements to
Privacy - Camera Usage Description (NSCameraUsageDescription) is required for using the camera and
Privacy - Photo Library Additions Usage Description (NSPhotoLibraryUsageDescription) when using
UIImageWriteToSavedPhotosAlbum() for storing photos. Values of those keys are localised descriptions which are shown when app requests to use the camera or when adding the photo to the library.
Setting up user interface for taking photos is quite easy thanks to UIImagePickerController. All in all it was a three step process: configure picker, add privacy statements and handle images.
PhotoTaker (GitHub) Xcode 10, Swift 4.2