dmytro-anokhin / url-image

AsyncImage before iOS 15. Lightweight, pure SwiftUI Image view, that displays an image downloaded from URL, with auxiliary views and local cache.
MIT License
1.1k stars 96 forks source link

How to do a forced reload / refresh? #82

Closed nylz closed 4 years ago

nylz commented 4 years ago

Is your feature request related to a problem? Please describe. I've been searching pretty long for a solution, to force a reload to an image. How can I do that?

Describe the solution you'd like A simple "Reload" - function, that reloads and displays the new image. Maybe something like URLImageService.shared.refresh(with: url) Or just a simplier solution described, if there is one. So further investigation by others confronted with this question will stop here on your page in the future. ;-)

Describe alternatives you've considered I've googled a lot, but did not find a satisfying solution for this. I already had a subpage, to what I switched for 0.2 secs and back, to force a reload. works, but looks stupid and ugly.

Additional context p.e.: User is uploading a new user-avatar, but the previous version is still shown. I already can remove it from the cache due to your implementation of my previous request, but this does not reload / refresh it on the screen.

dmytro-anokhin commented 4 years ago

Hey, you can remove cached image by URL:

URLImageService.shared.removeCachedImage(with: url)
nylz commented 4 years ago

Hi, yes, i know, but this does not refresh the URLImage-Component in my current view. Only when I enter this view next time, it is reloaded. I want to trigger the URLImage to load the new version from server and display it, without refreshing everything else.

dmytro-anokhin commented 4 years ago

After removing cached image URLImage will load it again. But you must trigger update, for instance by changing you @State property.

nylz commented 4 years ago

Ok, this is not very beautiful, but it is working. Thank You so much. You can close this.

Explanation: I had a simple dynamic function before, that provided the Url. like (pseudocode) URLImage(url: getAvatarUrl(self.session.currentuser.id) ...)

now i changed it to

@State userAvatarUrl: URLRequest? = nil

if self.userAvatarUrl != nil {
  URLImage(url: self.userAvatarUrl! ...)
}
...
onAppear() {
   // load stuff and set the avatarUrl
}

and after uploading (onSuccess):

let prevUrl = self.avatarUrl ... (+ ?? default) self.avatarUrl = nil DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { self.avatarUrl = prevUrl } Pseudocde, coz the real is very much more complex due to many nested components... Next time, I'll consider this earlier. This was my first Swift-Project. ;-)