UIImageをURLから非同期でロードしたい時のextensions。エラー処理とか全く入れてないけど...
UIImageExtension.swift
extension UIImage {
class func loadAsyncFromURL(urlString: String, callback: (UIImage?) -> ()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
let url = NSURL(string: urlString)
var err: NSError?
let imageData = NSData(contentsOfURL: url!, options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)
var image: UIImage?
if let _data = imageData {
image = UIImage(data: _data)
dispatch_async(dispatch_get_main_queue(), {
callback(image)
})
}
})
}
}
使い方
UIImage.loadAsyncFromURL(path, {
(image: UIImage?) in
self.imageView.image = image
})