@@ -15,6 +15,9 @@ import SDWebImage
1515final class AnimatedImageModel : ObservableObject {
1616 @Published var image : PlatformImage ?
1717 @Published var url : URL ?
18+ @Published var successBlock : ( ( PlatformImage , SDImageCacheType ) -> Void ) ?
19+ @Published var failureBlock : ( ( Error ) -> Void ) ?
20+ @Published var progressBlock : ( ( Int , Int ) -> Void ) ?
1821}
1922
2023// Layout Binding Object
@@ -67,7 +70,15 @@ public struct AnimatedImage : ViewRepresentable {
6770 func updateView( _ view: AnimatedImageViewWrapper , context: ViewRepresentableContext < AnimatedImage > ) {
6871 view. wrapped. image = imageModel. image
6972 if let url = imageModel. url {
70- view. wrapped. sd_setImage ( with: url, placeholderImage: nil , options: webOptions, context: webContext)
73+ view. wrapped. sd_setImage ( with: url, placeholderImage: nil , options: webOptions, context: webContext, progress: { ( receivedSize, expectedSize, _) in
74+ self . imageModel. progressBlock ? ( receivedSize, expectedSize)
75+ } ) { ( image, error, cacheType, _) in
76+ if let image = image {
77+ self . imageModel. successBlock ? ( image, cacheType)
78+ } else {
79+ self . imageModel. failureBlock ? ( error ?? NSError ( ) )
80+ }
81+ }
7182 }
7283
7384 layoutView ( view, context: context)
@@ -178,17 +189,10 @@ public struct AnimatedImage : ViewRepresentable {
178189 view. setNeedsDisplay ( )
179190 #endif
180191 }
181-
182- public func image( _ image: PlatformImage ? ) -> Self {
183- imageModel. image = image
184- return self
185- }
186-
187- public func imageUrl( _ url: URL ? ) -> Self {
188- imageModel. url = url
189- return self
190- }
191-
192+ }
193+
194+ // Layout
195+ extension AnimatedImage {
192196 public func resizable(
193197 capInsets: EdgeInsets = EdgeInsets ( ) ,
194198 resizingMode: Image . ResizingMode = . stretch) -> AnimatedImage
@@ -236,6 +240,25 @@ public struct AnimatedImage : ViewRepresentable {
236240 }
237241}
238242
243+ // Completion Handler
244+ extension AnimatedImage {
245+ public func onFailure( perform action: ( ( Error ) -> Void ) ? = nil ) -> AnimatedImage {
246+ imageModel. failureBlock = action
247+ return self
248+ }
249+
250+ public func onSuccess( perform action: ( ( PlatformImage , SDImageCacheType ) -> Void ) ? = nil ) -> AnimatedImage {
251+ imageModel. successBlock = action
252+ return self
253+ }
254+
255+ public func onProgress( perform action: ( ( Int , Int ) -> Void ) ? = nil ) -> AnimatedImage {
256+ imageModel. progressBlock = action
257+ return self
258+ }
259+ }
260+
261+ // Initializer
239262extension AnimatedImage {
240263 public init ( url: URL ? , placeholder: PlatformImage ? = nil , options: SDWebImageOptions = [ ] , context: [ SDWebImageContextOption : Any ] ? = nil ) {
241264 self . webOptions = options
0 commit comments