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() {
        super.viewDidLoad()
        
        let url = NSURL(string: "https://....JPG")!
        
        let imageSize : CGFloat = 200
        let imageView = UIImageView(frame: CGRectMake(0, 0, imageSize, imageSize))
        imageView.center = view.center
        
        NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) in
            
            if let error = error {
                print("Image read error \(error)")
                return
            }
            
            imageView.image = UIImage(data: data!)
        }).resume()
        
        //Synchronous Method without using NSURLSession
        //imageView.image = UIImage(data: NSData(contentsOfURL: url!)!)
        
        //Scale the image with the original aspect ratio
        imageView.contentMode = UIViewContentMode.ScaleAspectFit
        
        view.addSubview(imageView)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

No comments:

Post a Comment