From 4c4b868b79b2fdd075ba62eb914228afe8e35661 Mon Sep 17 00:00:00 2001 From: DreamPiggy Date: Mon, 18 Mar 2024 17:21:42 +0800 Subject: [PATCH] Fix the issue for WebImage when url is nil will not cause the reloading --- .../SDWebImageSwiftUIDemo/ContentView.swift | 39 ++++++++++++++++++- SDWebImageSwiftUI/Classes/WebImage.swift | 9 +++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/Example/SDWebImageSwiftUIDemo/ContentView.swift b/Example/SDWebImageSwiftUIDemo/ContentView.swift index e27bdb7..743af5b 100644 --- a/Example/SDWebImageSwiftUIDemo/ContentView.swift +++ b/Example/SDWebImageSwiftUIDemo/ContentView.swift @@ -17,6 +17,43 @@ class UserSettings: ObservableObject { #endif } +// Test Switching nil url +struct ContentView: View { + @State var isOn = false + @State var animated: Bool = false // You can change between WebImage/AnimatedImage + + var url: URL? { + if isOn { + .init(string: "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c1/Google_%22G%22_logo.svg/1024px-Google_%22G%22_logo.svg.png") + } else { + nil + } + } + + var body: some View { + VStack { + Text("\(animated ? "AnimatedImage" : "WebImage")") + Spacer() + if animated { + AnimatedImage(url: url) + .resizable() + .scaledToFit() + .frame(width: 100, height: 100) + } else { + WebImage(url: url) + .resizable() + .scaledToFit() + .frame(width: 100, height: 100) + } + Button("Toggle \(isOn ? "nil" : "valid") URL") { + isOn.toggle() + } + Spacer() + Toggle("Switch", isOn: $animated) + } + } +} + // Test Switching url using @State struct ContentView2: View { @State var imageURLs = [ @@ -63,7 +100,7 @@ struct ContentView2: View { } } -struct ContentView: View { +struct ContentView3: View { @State var imageURLs = [ "http://assets.sbnation.com/assets/2512203/dogflops.gif", "https://raw.githubusercontent.com/liyong03/YLGIFImage/master/YLGIFImageDemo/YLGIFImageDemo/joy.gif", diff --git a/SDWebImageSwiftUI/Classes/WebImage.swift b/SDWebImageSwiftUI/Classes/WebImage.swift index 457b6e6..4b0d091 100644 --- a/SDWebImageSwiftUI/Classes/WebImage.swift +++ b/SDWebImageSwiftUI/Classes/WebImage.swift @@ -163,6 +163,7 @@ public struct WebImage : View where Content: View { } } else { content((imageManager.error != nil) ? .failure(imageManager.error!) : .empty) + setupPlaceholder() // Load Logic .onPlatformAppear(appear: { self.setupManager() @@ -326,6 +327,14 @@ public struct WebImage : View where Content: View { } } } + + /// Placeholder View Support + func setupPlaceholder() -> some View { + let result = content((imageManager.error != nil) ? .failure(imageManager.error!) : .empty) + // Custom ID to avoid SwiftUI engine cache the status, and does not call `onAppear` when placeholder not changed (See `ContentView.swift/ContentView2` case) + // Because we load the image url in placeholder's `onAppear`, it should be called to sync with state changes :) + return result.id(imageModel.url) + } } // Layout