Skip to content

Commit 74eb6b5

Browse files
committed
Fix the issue that WebImage's onSuccess does not get called when memory cache hit for new created View Struct
1 parent 3353deb commit 74eb6b5

File tree

2 files changed

+9
-4
lines changed

2 files changed

+9
-4
lines changed

SDWebImageSwiftUI/Classes/ImageManager.swift

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ class ImageManager : ObservableObject {
1919
weak var currentOperation: SDWebImageOperation? = nil
2020
var isSuccess: Bool = false // true means request for this URL is ended forever, load() do nothing
2121
var isIncremental: Bool = false // true means during incremental loading
22+
var isFirstLoad: Bool = true // false after first call `load()`
2223

2324
var url: URL?
2425
var options: SDWebImageOptions
@@ -39,6 +40,7 @@ class ImageManager : ObservableObject {
3940
}
4041

4142
func load() {
43+
isFirstLoad = false
4244
if currentOperation != nil {
4345
return
4446
}

SDWebImageSwiftUI/Classes/WebImage.swift

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,16 @@ public struct WebImage : View {
3232
/// - Parameter context: A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
3333
public init(url: URL?, options: SDWebImageOptions = [], context: [SDWebImageContextOption : Any]? = nil) {
3434
self.imageManager = ImageManager(url: url, options: options, context: context)
35-
// load remote image here, SwiftUI sometimes will create a new View struct without calling `onAppear` (like enter EditMode) :)
36-
// this can ensure we load the image, SDWebImage take care of the duplicated query
37-
self.imageManager.load()
3835
}
3936

4037
public var body: some View {
41-
Group {
38+
// load remote image when first called `body`, SwiftUI sometimes will create a new View struct without calling `onAppear` (like enter EditMode) :)
39+
// this can ensure we load the image, and display image synchronously when memory cache hit to avoid flashing
40+
// called once per struct, SDWebImage take care of the duplicated query
41+
if imageManager.isFirstLoad {
42+
imageManager.load()
43+
}
44+
return Group {
4245
if imageManager.image != nil {
4346
if animated {
4447
if currentFrame != nil {

0 commit comments

Comments
 (0)