Last active
June 20, 2017 08:01
-
-
Save celian-m/90c2beebbbc7946b907df078a0b764aa to your computer and use it in GitHub Desktop.
ImageLoader
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 | |
struct ImageCache { | |
private var cache : [URL : Data] = [:] | |
static var worker : ImageCache = { | |
return ImageCache() | |
}() | |
static func addToCache(url : URL, data : Data) { | |
worker.cache[url] = data | |
} | |
static func fromCache(url : URL) -> Data? { | |
return worker.cache[url] | |
} | |
} | |
class CMImageView : UIImageView { | |
var task : URLSessionTask? | |
func assignImage(url : URL, completion : (() -> ())? = nil ) { | |
self.image = nil | |
if task != nil { | |
task?.cancel() | |
task = nil | |
} | |
if let data = ImageCache.fromCache(url: url) { | |
self.image = UIImage(data: data) | |
completion?() | |
return | |
} | |
task = WS.worker.session.dataTask(with: url, completionHandler: { (data, response, error) in | |
guard let data = data else { return } | |
ImageCache.addToCache(url: url, data: data) | |
self.image = UIImage(data: data) | |
completion?() | |
}) | |
task?.resume() | |
} | |
func assignImage( videoURL : URL, completion: (() -> ())? = nil) { | |
if let data = ImageCache.fromCache(url: videoURL) { | |
self.image = UIImage(data: data) | |
completion?() | |
return | |
} else { | |
DispatchQueue.global().async { | |
let asset = AVAsset(url: videoURL) | |
let imageGenerator = AVAssetImageGenerator(asset: asset) | |
let time = CMTimeMake(1, 1) | |
if let imageRef = try? imageGenerator.copyCGImage(at: time, actualTime: nil) { | |
let thumbnail = UIImage(cgImage:imageRef) | |
if let data = UIImagePNGRepresentation(thumbnail) { | |
ImageCache.addToCache(url: videoURL, data:data) | |
} | |
DispatchQueue.main.async { | |
self.image = thumbnail | |
completion?() | |
} | |
}else{ | |
DispatchQueue.main.async { | |
completion?() | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment