I have a list of URL's that provide a location to an Image resource. I managed to find a solution, but I feel as if there is a much better way than the procedure shown in the code below. Any tips on how to improve this method to retrieve images asynchronously is greatly appreciated!
Isn't something weird about calling the completionHandler after I append each item, AND adding 1 to index (i), outside of async block, meaning that the while loop iterates to the next url item before the last url has been fully handled??
typealias imagesHandler = (_ images: [UIImage]) -> Void
func fetchImages(forUser user: User, completionHandler: imagesHandler?) {
var images = [UIImage]()
self.fetchImageUrlList(forUser: user) { (urlList: [URL]) in
var i = 0
while i <= urlList.count - 1 {
let request = URLRequest(url: urlList[i])
let dataTask = URLSession(configuration: .default).dataTask(with: request, completionHandler: {
(data: Data?, response: URLResponse?, error: Error?) in
guard error == nil else { return }
guard let data = data else { return }
guard let image = UIImage(data: data) else { return }
images.append(image)
completionHandler?(Array(Set(images)))
})
i += 1
dataTask.resume()
}
}
}