Skip to content

Instantly share code, notes, and snippets.

@ksmandersen
Last active January 20, 2016 14:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ksmandersen/6ace1da0d4372202506e to your computer and use it in GitHub Desktop.
Save ksmandersen/6ace1da0d4372202506e to your computer and use it in GitHub Desktop.
Loading a UIImage into a UIImageView from a NSURL using Forbind
import UIKit
import Forbind
import ForbindExtensions
enum LoadingState {
case NotSet
case Loading
case Loaded
}
class RemoteImageView: UIImageView {
private(set) var URL: NSURL?
private(set) var state: LoadingState = .NotSet
private var imagePromise: Promise<Result<UIImage>>?
private var placeholderImage: 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 cancelImage() {
self.imagePromise = nil
if let placeholder = self.placeholderImage {
self.image = placeholder
}
}
func loadImage(URL: NSURL, placeholderImage: UIImage? = nil) {
self.placeholderImage = placeholderImage
self.image = placeholderImage
self.URL = URL
sendImageRequest()
}
private func sendImageRequest() {
guard let URL = self.URL else { return }
let session = NSURLSession.sharedSession()
let dataTask = session.dataTask(URL)
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