I need to grab another image in case the initial one fails and Im having a hard time figuring how to do this with SDWebImageSwiftUI.
On regular SDWebImage I could just do an extension on UIImage such as:
self.sd_setImage(with: url) { (image, error) in
if (error != nil) {
self.image = image
} else {
self.sd_setImage(with: secondURL)
}
}
Any clue as to how to do the same on SDWebImageSwiftUI?
CodePudding user response:
You could use the onFailure
property on WebImage
. Something like this could work:
import SDWebImageSwiftUI
struct DoubleImageView: View {
@State var url = URL(string: "https://via.placeholder.com/150x150.jpg")
var body: some View {
WebImage(url: url)
.placeholder(Image(systemName: "person").resizable())
.onFailure { _ in
url = URL(string: "https://via.placeholder.com/72x72.jpg")
}
.resizable()
.frame(width: 100, height: 100)
}
}
Just change the initial url to "https://via.placeholder.com"
and that will cause a failure to load the image, which will in turn update the url
and cause the image to be reloaded with the new url
.
CodePudding user response:
import SDWebImageSwiftUI
struct ContentView: View {
var body: some View {
WebImage.init(url: URL(string: "https://via.placeholder.com/300/09f.png/fff"))
.placeholder(Image(uiImage: #imageLiteral(resourceName: "placeholder")))
}
}
The above code worked for me, Hope it will work for you :)