I'm trying to create a simple ImageDownloader framework in swift.
What I'd like to achieve:
- Able to download images with given URLs
- Cache with url string
So fetching just one image is no problem, I just used func dataTask(with url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask from URLSession to get the data and pass it into UIImage.
However, my question is, how should I change it into a framework that supports concurrent download many images at the same time?
Should I used OperationQueue and every time the task is created with an url, add that task into the queue? Is this necessary?? e.g.:
let oq = OperationQueue()
let urlArray = ["url1", "url2" ....]
for url in urlArray {
oq.addOperation {
self?.fetchImage(with: url, placeHolder: nil) { [weak self] result in
switch result {
//...
}
}
}
Thanks!
No, it uses a closure to return a result because it already does this for you, you are not going to block on the call, you will trigger downloading, probable using a thread, and then when its finished it will call the result closure, because of this you need to be aware that your app state could have changed when you get your result.