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) } }
Brilliant contribution thanks
LikeLiked by 1 person
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.
LikeLike
Thank you for your comment.
Is the class where you define the method loadImageFromUrl
LikeLike
(“use of unresolved identifier ImageHelper”) But I am same class with loadImageFromUrl method
LikeLike
(“use of unresolved identifier ImageHelper”). What wrong? Same class with loadImageFromUrl method
LikeLike
Just use loadImageFromUrl(…) if you are in the same class
LikeLike
Thank you!!! This is a great contribution. It works perfectly.
LikeLike
Thank you !
LikeLike