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) } }
Your feedback is important…