Skip to content

Instantly share code, notes, and snippets.

@neoneye
Forked from ksmandersen/RemoteImage.swift
Created January 6, 2016 17:03
Show Gist options
  • Save neoneye/88ea8bbae2fc36b68477 to your computer and use it in GitHub Desktop.
Save neoneye/88ea8bbae2fc36b68477 to your computer and use it in GitHub Desktop.
import UIKit
import Forbind
import ForbindExtensions
class RemoteImageView: UIImageView {
private(set) var URL: NSURL?
private var imagePromise: Promise<Result<UIImage>>?
init() {
super.init(image: nil)
}
convenience init(URL: NSURL, placeholderImage: UIImage) {
self.init()
loadImage(URL, placeholderImage: placeholderImage)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func loadImage(URL: NSURL, placeholderImage: UIImage? = nil) {
self.image = placeholderImage
self.URL = URL
sendImageRequest()
}
private func sendImageRequest() {
guard let URL = self.URL else { return }
let session = NSURLSession.sharedSession()
let request = NSURLRequest(URL: URL)
let dataTask = session.dataTask(request)
self.imagePromise = dispatchAsync(dataTask => { UIImage(data: $0.0) }, queue: dispatch_get_main_queue())
self.imagePromise?.getValueWeak { [weak self] result in
if let image = result.okValue {
self?.image = image
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment