Today we will be creating an image view that contains an image loaded from a url! This is something typically done when setting a profile photo stored on a server.
The end result will look something like this!
In the image above, I am grabbing the information through Google’s Sign In API, which presents a URL to the user’s profile photo and their full name after they sign in.
Creating the View
To create the view, drag an Image View onto your Storyboard and place it on the horizontal grid line to make sure that it is centered horizontally.
With the Image View selected, click on the “Align” menu item at the bottom right of XCode and check “Horizontally in Container” to add a Horizontal center constraint.
Then there will be some red lines surrounding your Image View. To fix this click on the “Resolve Auto Layout Issues” menu item and click “Add Missing Constraints.
Setting the Image View’s Photo
I created this method below that you can copy to set your profile Image View. Each line of code is explained in the numbered bullets below which correspond the the commented numbers in the code.
In this code example I have an outlet to the Image View we added earlier which is named as “profileImageView”.
- Unwrap the URL optional. (It is possible to call this method with a non existent URL)
- Create an NSData object that contains the data from the image retrieved from the URL. This will handle the fetching of the image for you!
- Create a circular Image View. This is achieved by setting the corner radius and clipping the Image to the set radius
- Finally set the image of the Image View to a UIImage object created from the data!
That’s it! It is very easy in Swift to set an image from a URL and design the Image View however you like!