Setting an Image View from URL

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!

Screen Shot 2016-12-10 at 9.23.49 PM.png

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.

Screen Shot 2016-12-10 at 9.26.46 PM.png

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.

Screen Shot 2016-12-10 at 9.26.54 PM.png

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”.

Screen Shot 2016-12-10 at 9.33.13 PM.png

  1. Unwrap the URL optional. (It is possible to call this method with a non existent URL)
  2. 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!
  3. Create a circular Image View. This is achieved by setting the corner radius and clipping the Image to the set radius
  4. 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!