Wednesday, April 27, 2016

Asynchronously Display an Web Image with NSURLSession.sharedSession().dataTaskWithURL

To display an image on the Internet in Swift 2.2 with Xcode 7.3 using asynchronous download method, modify ViewController.swift as:

import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        let url = NSURL(string: "https://....JPG")!
        let imageSize : CGFloat = 200
        let imageView = UIImageView(frame: CGRectMake(0, 0, imageSize, imageSize)) =
        NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) in
            if let error = error {
                print("Image read error \(error)")
            imageView.image = UIImage(data: data!)
        //Synchronous Method without using NSURLSession
        //imageView.image = UIImage(data: NSData(contentsOfURL: url!)!)
        //Scale the image with the original aspect ratio
        imageView.contentMode = UIViewContentMode.ScaleAspectFit
    override func didReceiveMemoryWarning() {


No comments:

Post a Comment