Skip to content

Instantly share code, notes, and snippets.

@aybekckaya
Last active May 16, 2019 11:52
Show Gist options
  • Select an option

  • Save aybekckaya/f0e7aff07f77d5a0241aa05171dd6725 to your computer and use it in GitHub Desktop.

Select an option

Save aybekckaya/f0e7aff07f77d5a0241aa05171dd6725 to your computer and use it in GitHub Desktop.
import UIKit
class ImageKit: NSObject {
private let group:DispatchGroup = DispatchGroup()
override init() {
super.init()
}
func download(images:[String] , completion:@escaping ((_ finished:Bool , _ downloadedImage:UIImage?)->()) ) {
images.forEach { imgURL in
group.enter()
self.asyncTask(imageURL: imgURL, completion: { [weak self] image in
guard let self = self else { return }
completion(false, image)
self.group.leave()
})
}
group.notify(queue: DispatchQueue.main) { completion(true , nil ) }
}
private func asyncTask(imageURL:String , completion:@escaping ( (_ image:UIImage?)->() ) ) {
DispatchQueue.global(qos: .background).async {
guard let url:URL = URL(string: imageURL) , let imageData:Data = try? Data(contentsOf: url) , let image:UIImage = UIImage(data: imageData) else {
completion(nil)
return
}
DispatchQueue.main.async { completion(image) }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment