Created
August 7, 2016 15:07
-
-
Save anonymous/88a276c8eb08ec60a796c25ffcf4383c to your computer and use it in GitHub Desktop.
Async Image download with Swift 2.2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import Foundation | |
class ViewController: UIViewController { | |
@IBOutlet var mainTitle: UILabel! | |
@IBOutlet var mainPoster: UIImageView! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view, typically from a nib. | |
super.viewDidLoad() | |
// Do any additional setup after loading the view, typically from a nib. | |
if let checkedUrl = NSURL(string: "http://www.apple.com/euro/ios/ios8/a/generic/images/og.png") { | |
mainPoster.contentMode = .ScaleAspectFit | |
downloadImage(checkedUrl) | |
} | |
} | |
func downloadImage(url: NSURL){ | |
print("Download Started") | |
print("lastPathComponent: " + (url.lastPathComponent ?? "")) | |
getDataFromUrl(url) { (data, response, error) in | |
dispatch_async(dispatch_get_main_queue()) { () -> Void in | |
guard let data = data where error == nil else { return } | |
print(response?.suggestedFilename ?? "") | |
print("Download Finished") | |
self.mainPoster.image = UIImage(data: data) | |
} | |
} | |
} | |
func getDataFromUrl(url:NSURL, completion: ((data: NSData?, response: NSURLResponse?, error: NSError? ) -> Void)) { | |
NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in | |
completion(data: data, response: response, error: error) | |
}.resume() | |
} | |
} | |
extension UIImageView { | |
func downloadedFrom(link link:String, contentMode mode: UIViewContentMode) { | |
guard | |
let url = NSURL(string: link) | |
else {return} | |
contentMode = mode | |
NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in | |
guard | |
let httpURLResponse = response as? NSHTTPURLResponse where httpURLResponse.statusCode == 200, | |
let mimeType = response?.MIMEType where mimeType.hasPrefix("image"), | |
let data = data where error == nil, | |
let image = UIImage(data: data) | |
else { return } | |
dispatch_async(dispatch_get_main_queue()) { () -> Void in | |
self.image = image | |
} | |
}).resume() | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment