Loading images from URL in Swift

Shawon Ashraf
The Startup
Published in
3 min readSep 3, 2019

Images and URLs

You’re writing the front-end of a fancy website. You have to load images from a remote server and you have the url. What do you do? You take sip from your cup of coffee, grin and pull some HTML trickery. Just like this -

<img src="some_url" alt="some_image">

And that’s it, the day (or, night) is saved, thanks to, the PowerPuff Girls! Oh wait, your image tag!

How’s that for a mobile app dev?

App devs are an unlucky folk. They don’t get to enjoy the niceties web developers have. It’s a very melancholic way to put it, but their life isn’t as straightforward as loading an image with an HTML tag.

Okay let’s get back on topic

Let’s say you want to have the same life of a front-end web dev, meaning you want to load images from remote servers in your image views without sacrificing a virgin (that’s how it is actually), how do you do it?

Preparing

Create a Single View iOS project. Add an ImageView to your View and create an outlet for it (if you're a beginner, ctrl + click and drag it to create a variable). Add constraints if you feel necessary, though not mandatory for our discussion.

Initial storyboard view with an imageview

The hard way — URLSessionDataTask

For this, you need to init an URLSession, then create and start a datatask, add in an async handler for data task completion and then set the image. Oh wait! You can't use the main thread to set the image. You should fire up a separate thread via dispatchqueue to do so.

And to set the image on an ImageView (finally!) -

Shawon Ashraf
The Startup

Metalhead, Apple Sheep, Horrible Guitar Player, and, I use tabs instead of spaces. P.S. — I hate Vim and Emacs.