Mini Tutorial for PhotoKit
I’m creating a short tutorial on fetching an image from photo library and displaying that image on our storyboard...
Tojo Batsuuri - Lead Developer + Designer
Sep 16, 2019
I’m creating a short tutorial on fetching an image from photo library and displaying that image on our storyboard. This will ask for user permission and then show the image automatically. This tutorial will take the first image from the library and display it. We will be using the PhotoKit, for more information read the Apple guide. We begin by creating a new method called loadImage, this method will return an optional UIImage. We will use this method to grab our image to display on our screen. Make it optional just in case we can’t fetch any images from our photo library. https://gist.github.com/tbatsuur/45e2a6d829103b3ab2e3dd065ecf14f4#file-loadimages-swift
Create a manager object that we will use to fetch photo assets. PHImageManager caches the asset images, allowing for our re-requested assets to load faster. Default method returns the manager object.
Next, create fetchResult of type PHFetchResult. This class gives us an ordered list of assets that is returned from Photos fetch method. PHAsset instance represents the images we will retrieve. fetchAssets method will retrieve images. Options lets us filter and sort the assets we fetched and fetchOptions is the method we will create next.
We instantiate PHFetchOptions class. This class will allow us to filter, sort and manage results from our fetched assets.
sortDescriptors property specifies the order of our fetched objects. We will use an array of NSSortDescriptor using set of key paths and sort order. We will use creationDate key to sort our assets based on the date those assets were created. You can read more about key paths here.
Request options method will return PHImageRequestOptions. We will use this method to affect how the images are delivered. https://gist.github.com/tbatsuur/45563de97b12a61ed826697ef7b7920a#file-requestoptions-swift
We set the Boolean for isSynchronous to true.
This property lets us set up the quality of the image or the delivery speed of our fetch request. We return requestOptions, we will use this method for our loadImage( ) method.
Let’s go back to our loadImage method and add the following code:
We will create an optional image and we will return this property once we are done without functionality.
Use the requestImage to find out specified asset. We will use the fetchResult object we created earlier to fetch an asset at specific index by using the object(at: ) method. We also specify our image size and content mode which tells how to fit the image to the aspect ratio of the requested size. We pass our requestOptions( ) method we created into the options parameter. This tells how our request will be handled.
Create a guard statement to make sure our img isn’t empty, else we just return our image as nil. Then we will finally return our image.
Next, in your storyboard. Add an ImageView into your View Controller and connect the outlet to your swift file. @IBOutlet weak var imageView: UIImageView! We will now create a photoAuthorization method that will deal with user permissions. This method will check if the user gives us access to the photo library, if we are authorized we will run rest of our methods. If not we will just print a statement. If you wish, you can use UIAlertController to prompt an alert message. https://gist.github.com/tbatsuur/1dd49db6b91aeba1a3234e9f85f4f51d#file-photoauthorization-swift
This checks our current authorization status. PHPhotoLibrary object represents the entire set of assets managed by the Photos app. The switch statement is used to check our status and determine what we should do.
If the authentication was successful, we will use our loadImage method to return an image to the imageView outlet.
RequestAuthorization create a prompt for the user to accept or decline the use of photo library.
If it’s the users first time accessing the app, we don’t want our image to load without authorization prompt. We will load our image call asynchronously.
Add the photoAuthorization method into the viewDidLoad.
https://gist.github.com/tbatsuur/0eafde49eee0228fb3d8d2c9d00e02a8#file-viewdidload-swift Finally, we will also need to ask for user permission on the Info.plist. You can either add the “Privacy — Photo Library Usage Description” or use manually add the permission on the source code: <key>NSPhotoLibraryUsageDescription</key><string>Need access to photo library</string> That’s it, pretty simple to set up. Now you can load the image upon initiation of the view controller. Hope you took away some useful pieces of code!