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

Published by

on

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 responses to “Swift 2 examples – #1 Loading an image from a URL”

  1. Helmut Otto Avatar
    Helmut Otto

    Brilliant contribution thanks

    Liked by 1 person

  2. G Thomas Avatar
    G Thomas

    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

  3. Juan Carlos Sánchez Avatar

    Thank you for your comment.

    Is the class where you define the method loadImageFromUrl

    Like

  4. Nyan Lin Tun Avatar
    Nyan Lin Tun

    (“use of unresolved identifier ImageHelper”) But I am same class with loadImageFromUrl method

    Like

  5. Nyan Lin Tun Avatar
    Nyan Lin Tun

    (“use of unresolved identifier ImageHelper”). What wrong? Same class with loadImageFromUrl method

    Like

  6. Juan Carlos Sánchez Avatar

    Just use loadImageFromUrl(…) if you are in the same class

    Like

  7. Melissa Rojas (@KaMeRoLi) Avatar

    Thank you!!! This is a great contribution. It works perfectly.

    Like

  8. Clever Almeida Avatar

    Thank you !

    Like

Your feedback is important…

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

Blog at WordPress.com.