Loading in a Loop
godefroydlb opened this issue · comments
I am using URL Image to download several images (6images of 3Mb approx) in Loop.
Only the last image is downloading correctly. I think it is due to the queue management.
The fetchImage method launch initial and in progress steps but no success.
What is the good way to manage it in a loop ?
`let iCloudDocumentsURL = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents")
.appendingPathComponent("PhotosVehicules")
.appendingPathComponent(vehicule.immat)
.appendingPathComponent(pointage)
do {
print(iCloudDocumentsURL?.standardizedFileURL.absoluteString)
let items = try FileManager.default.contentsOfDirectory(atPath: iCloudDocumentsURL!.path)
for item in items{
let photoStringURL = iCloudDocumentsURL!
.appendingPathComponent(item)
if(FileManager.default.fileExists(atPath: photoStringURL.path))
{
print("File exist")
fetchImageToken = URLImageService.shared.fetchImage(photoStringURL) { result in
switch result {
case .success(let imageInfo):
self.pictures.append(UIImage(cgImage: imageInfo.cgImage))
print("I have loaded picture : " + String(self.pictures.count) + photoStringURL.lastPathComponent)
break
case .failure(let error):
print("error")
break
}
}
}
}
} catch {
print("catch")
}
extension URLImageService {
func fetchImage(_ url: URL,
options: URLImageOptions? = nil,
completion: @escaping (_ result: Result<ImageInfo, Error>) -> Void) -> Any {
let remoteImage = makeRemoteImage(url: url, options: options)
let cancellable = remoteImage.$loadingState.sink { loadingState in
switch loadingState {
case .initial:
print("initial" + url.path)
break
case .inProgress:
print("progress" + url.path)
break
case .success(let transientImage):
print("success" + url.path)
completion(.success(transientImage.info))
case .failure(let error):
completion(.failure(error))
}
}
remoteImage.load()
return (remoteImage, cancellable)
}
}`
Hey, maybe new API can help: https://github.com/dmytro-anokhin/url-image#fetching-an-image
Hi Dmytro,
It is me again :-p. Sorry to bother you again, but would it be possible to have an helper as the last fetch method ?
Thank you for your work :-)
Hey, not sure if I fully understand, what exactly do you want the last fetch method to do?
Could you provide the same kind of example as you did for the fetch outside a view, but with this version with array and combine.
starting from an array of url and getting as result an array of images (cgimage)
Hey, there already is an example of loading multiple images in the documentation. For your case I would suggest to use map
operator on the items
array to convert it into an array of RemoteImagePublisher
:
let publishers = items.map { item in
let photoStringURL = iCloudDocumentsURL!.appendingPathComponent(item)
return URLImageService.shared.remoteImagePublisher(photoStringURL)
}