-
-
Save neoneye/88ea8bbae2fc36b68477 to your computer and use it in GitHub Desktop.
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 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