Swift 2 examples – #1 Loading an image from a URL

This post is part of my collection: Swift 2 – For Beginners.

In this example we will see how to load an image from a URL in a UIImageView. With the new version of iOS 7 it is not possible to make requests to non secure URLs, in other words the URL must be https and not http.

The first thing that we have to do to load images from a non secure URL is to add this to our Info.plist file:

	<key>NSAppTransportSecurity</key>
	<dict>
		<key>NSAllowsArbitraryLoads</key>
		<true/>
	</dict>

The loadImageFromUrl method will have two parameters:

  • url: String – URL of the image to load
  • view: UIImageView – View where the image will be loaded
    static func loadImageFromUrl(url: String, view: UIImageView){
        
        // Create Url from string
        let url = NSURL(string: url)!
        
        // Download task:
        // - sharedSession = global NSURLCache, NSHTTPCookieStorage and NSURLCredentialStorage objects.
        let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (responseData, responseUrl, error) -> Void in
            // if responseData is not null...
            if let data = responseData{
                
                // execute in UI thread
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    view.image = UIImage(data: data)
                })
            }
        }
        
        // Run task
        task.resume()
    }

Using the previous method we can very easily load an image from a URL inside our UIImageView. This is a nice page to get sample images http://dummyimage.com

class ViewController: UIViewController {
    @IBOutlet weak var imageView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        ImageHelper.loadImageFromUrl("http://dummyimage.com/200x200/000333/d2d4fa.png&text=Hello+Swift!", view: imageView)
    }
}

Hello Swift

8 thoughts on “Swift 2 examples – #1 Loading an image from a URL

  1. It looks great, but mine is stuck on ImageHelper (“use of unresolved identifier ImageHelper”). What have I done wrong? I am new to Swift and finding things impenetrable at times.

    Like

Your feedback is important...

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.