iosswiftimageswiftuisdwebimage

SDWebImageSwiftUI - How to load a fallback image if the first one fails?


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.

Any clue as to how to do this?


Solution

  • 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.