22
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[swift]画像を非同期でロードするextensions

Posted at

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
})
22
21
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?