AboutContact

Swift image from url: How to load UIImage from url

In this tutorial you'll see through an example how to load image from url using Swift. You'll see how to add in the storyboard the UIImageView component, how to load the image programmatically from URL and how to display the image data in your UIImageView.

Let's start by creating a new Swift iOS single view project and, once created, open the main.storyboard. You can turn the disable the use size classes feature off, from the file inspector section.

Layout definition: let's add the UIImageView component

In the default ViewController add the Image View component. Under the size inspector set a frame rectangle with a width of 100 and a height of 100.

swift: add the uiimage view component

Let's now add the constraints. Pick the align button and align the UIImageView component horizontally. Add also the top constraint and set the width and height constraints to 100.

swift: add uiimageview constraints 

 

Coding part: let's define the function that programmatically load the image from URL

Open the assistant editor and assign in the ViewController.swift class to the UIImage component a variable : call it image_view.

In the View_Controller.swift class, define the class that perform the asynchronous request. This function requires as an input the image url string, and the UIImageView reference (the variable defined using the assistand editor). You can reuse this function for every image you have to load, you have just to call it passing the image url string and the corresponding UIImageView reference, then as soon as the image data is ready the image will appear in the right view.

  @IBOutlet var image_view: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        load_image("https://www.kaleidosblog.com/tutorial/kaleidosblog.png", view:image_view)

        
    }



func load_image(image_url_string:String, view:UIImageView)
{
        
        var image_url: NSURL = NSURL(string: image_url_string)!
        let image_from_url_request: NSURLRequest = NSURLRequest(URL: image_url)
        
        NSURLConnection.sendAsynchronousRequest(
            image_from_url_request, queue: NSOperationQueue.mainQueue(),
            completionHandler: {(response: NSURLResponse!,
                                data: NSData!,
                                error: NSError!) -> Void in
                
                if error == nil && data != nil {
                    view.image = UIImage(data: data)
                }
                
        })
        
}

 

In the next tutorial you'll see how to load the images in a TableView Controller using the same load_image function, how to use core data to cache the images loaded from url and how to read them when needed, without  downloading them again.

If you enjoyed this tutorial, share it. You can fine more Swift tutorial here.

Download this example.

Leave a comment












AboutContactPrivacy