LazyImage: What is the correct way to reload reload an image after a network failure?
Closed this issue · 2 comments
grex commented
Thank you for this great library! My apologies if this question is obvious or has already been answered elsewhere (I couldn't find it).
Imagine we're using LazyImage
to display an image but due to a network failure or timeout, the image state has an error
. Is there a way to force reloading the image in this state? Or is this only possible by using FetchImage
and doing the reload through that?
Example based on the sample code form the docs:
LazyImage(url: URL(string: "https://example.com/image.jpeg")) { state in
if let image = state.image {
image.resizable().aspectRatio(contentMode: .fill)
} else if state.error != nil {
❓❓❓❓❓
// is there a way to programmatically reload the LazyImage here?
// `state` doesnt offer any such methods :\
} else {
...
}
}
kean commented
Hey, good question @grex. There is an example of this scenario in the SwiftUI preview of LazyImage
. Basically, you need to add an id
to the image view and increment it to force the view to reload.
private struct LazyImageDemoView: View {
@State var url = URL(string: "https://kean.blog/images/pulse/01.png")
@State var imageViewId = UUID()
var body: some View {
VStack {
LazyImage(url: url) { state in
if let image = state.image {
image.resizable().aspectRatio(contentMode: .fit)
}
}
.id(imageViewId) // Example of how to implement retry
Button("Retry") { imageViewId = UUID() }
}
}
}
#endif
grex commented
Amazing, thank you!