UIImage from URL with Swift

UIImage from URL tutorial: If you are new in Swift for iOS 8 and you want to load an image in a UIImage view from URL, then you are in the right place. In this tutorial you'll learn how to load an UIImage from URL with Swift.

Create a new single view swift project for iOS.

 From the Main.storyboard you can for simplicity turn off the use size classes option.

Now you can add, inside the view in the Main.storyboard, the Image view element. Once added the UIImage component, you can click on it and access on the size inspector section. Here, under the view section, you can set the frame rectangles to a size of 50 x 50. In the screenshot below I've highlighted where to find the size inspector and the section where to edit the width and the height of the UIImage component. 

Now the code part can begin. The first thing you've to do is to connect the UIImage element that you've previously added to a variable. In this way you can access to the UIImage component directly through this variable. With the Main.storyboard opened just click on the assistant editor. It's the button posed on the right-top defined by the two circles I've reported in the figure below.

The assistant editor is a great tool that allows you to conenct a UI component to a variable or to an action. Once pressed, the view will split into two parts. The one on the top is your Main.storyboard, while on the bottom the view controller part will be displayed. The View Controller is the class that is called as a first thing when your application is starting. By pressing the CTRL button, you can click on the UIImage component in the Main.storyboard and with your mouse you've to drag your mouse to the bottom part of the screen, just above the viewDidLoad function. Once released the mouse, you can type the variable name and press Connect.

Now you can exit from the assistant editor by pressing the button on the left of the assistant editor.

You can now open the ViewController.swift class and write the load_image function. The image_element variable is the name of the variable you've previously choosen to connect the element. This function call the iOS sendAsynchronousRequest function that performs a background asyncronous request.  

func load_image(urlString:String)
{

var imgURL: NSURL = NSURL(string: urlString)!
let request: NSURLRequest = NSURLRequest(URL: imgURL)
NSURLConnection.sendAsynchronousRequest(
request, queue: NSOperationQueue.mainQueue(),
completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
if error == nil {
self.image_element.image = UIImage(data: data)
}
})

}

 

You can now load the image in the viewDidLoad function by writing:

load_image("http://www.kaleidosblog.com/tutorial/kaleidosblog.png")

 

You can download the code for this example here.

UPDATE: download the swift 2 code example from here