skip to Main Content
Download Image Url Using Nsurlconnection

iOS Dev 101: Download an image with NSURLConnection

There are several cases when you need to download an image from a specific url, so it is better that you know how to do it easily and effectively. Today I’m gonna show you how it can be achieved using NSURLConnection.

The case is that you downloaded and parsed your .json data and now you have a String of an url that you suppose to be displaying. How you do that? Well, surely you cannot set that string to be the image of your UIImageView, so you need to call that url and download it.

Download the url using NSURLConnection

NSURLConnection comes in handy when you don’t want to use third party libraries like AFNetworking, although that library is awesome.

What we need to do is create the request object that will hold the url and send the request in the background, not to block the UI.

 

As you can see, we create a request, send it with the NSURLConnection method: sendAsynchronousRequest:queue:completionHandler: and we handle the results. If we get an error, than of course we either need to display an alert (AlertView or custom alert solution within your app) or try to download the image again. If that was successful than create an UIImage from the NSData that we received and in the main block update the UIImageView with the image that we just created.

Don’t block the main thread

Probably you heard this everywhere because it is true, if you block the main thread than your app will be probably rejected from the App Store and you need to solve this problem as soon as possible.

Blocking the main thread? What does it even mean?

I’m sure you had this experience a lot of times before, when you used an app and you wanted to scroll through the list of cars for example that are available on the market, but the UI was frozen (you couldn’t scroll anymore) until the certain image was downloaded. The reason for this, is that you/they are downloading data on the main thread which should only be used to display UI related information, setting an UIImage to an UIImageView, setting a label, etc.

No sample code this time, because it is really just a small tip and trick that will help you on your way to create better iOS apps. Make sure to follow us to receive new tutorials, tips and tricks weekly to make you the best developer ever