diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index c093458d0..ab3a90711 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -14,15 +14,13 @@ jobs: 'watchOS Simulator,name=Apple Watch Series 8 (41mm)' ] xcode: [ - '15.2', - '15.3' + '15.3', + '15.4' ] steps: - uses: actions/checkout@v4 - - uses: ruby/setup-ruby@v1 - with: - bundler-cache: true - self-hosted: true + - name: Install Gems + run: bundle install - name: Run tests env: DESTINATION: platform=${{ matrix.destination }} diff --git a/.ruby-version b/.ruby-version index 15a279981..bea438e9a 100644 --- a/.ruby-version +++ b/.ruby-version @@ -1 +1 @@ -3.3.0 +3.3.1 diff --git a/Kingfisher.xcodeproj/project.pbxproj b/Kingfisher.xcodeproj/project.pbxproj index 907f0124f..f354adfc5 100644 --- a/Kingfisher.xcodeproj/project.pbxproj +++ b/Kingfisher.xcodeproj/project.pbxproj @@ -28,7 +28,6 @@ 4BD821622189FC0C0084CC21 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4BD821612189FC0C0084CC21 /* SessionDelegate.swift */; }; 4BD821672189FD330084CC21 /* SessionDataTask.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4BD821662189FD330084CC21 /* SessionDataTask.swift */; }; 4BE688F722FD513100B11168 /* NSButton+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = D12AB6AD215D2BB50013BA68 /* NSButton+Kingfisher.swift */; }; - 4BE688F822FD513700B11168 /* WKInterfaceImage+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = D12AB6AF215D2BB50013BA68 /* WKInterfaceImage+Kingfisher.swift */; }; 76FB4FD2262D773E006D15F8 /* GraphicsContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 76FB4FD1262D773E006D15F8 /* GraphicsContext.swift */; }; C9286407228584EB00257182 /* ImageProgressive.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9286406228584EB00257182 /* ImageProgressive.swift */; }; D1132C9725919F69003E528D /* KFOptionsSetter.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1132C9625919F69003E528D /* KFOptionsSetter.swift */; }; @@ -119,7 +118,7 @@ D1F1F6FF24625EC600910725 /* RetryStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1F1F6FE24625EC600910725 /* RetryStrategyTests.swift */; }; D8FCF6A821C5A0E500F9ABC0 /* RedirectHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = D8FCF6A721C5A0E500F9ABC0 /* RedirectHandler.swift */; }; D9638BA61C7DC71F0046523D /* ImagePrefetcherTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D9638BA41C7DC71F0046523D /* ImagePrefetcherTests.swift */; }; - DCEB2842257E4BE100D7A610 /* TVMonogramView+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCEB2841257E4BE100D7A610 /* TVMonogramView+Kingfisher.swift */; }; + E9E3ED8B2B1F66B200734CFF /* HasImageComponent+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9E3ED8A2B1F66B200734CFF /* HasImageComponent+Kingfisher.swift */; }; F72CE9CE1FCF17ED00CC522A /* ImageModifierTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F72CE9CD1FCF17ED00CC522A /* ImageModifierTests.swift */; }; /* End PBXBuildFile section */ @@ -190,7 +189,6 @@ D12AB6AC215D2BB50013BA68 /* ImageView+Kingfisher.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ImageView+Kingfisher.swift"; sourceTree = ""; }; D12AB6AD215D2BB50013BA68 /* NSButton+Kingfisher.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "NSButton+Kingfisher.swift"; sourceTree = ""; }; D12AB6AE215D2BB50013BA68 /* UIButton+Kingfisher.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIButton+Kingfisher.swift"; sourceTree = ""; }; - D12AB6AF215D2BB50013BA68 /* WKInterfaceImage+Kingfisher.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "WKInterfaceImage+Kingfisher.swift"; sourceTree = ""; }; D12AB6B1215D2BB50013BA68 /* Kingfisher.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Kingfisher.swift; sourceTree = ""; }; D12AB6B2215D2BB50013BA68 /* KingfisherError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = KingfisherError.swift; sourceTree = ""; }; D12AB6B3215D2BB50013BA68 /* KingfisherManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = KingfisherManager.swift; sourceTree = ""; }; @@ -297,7 +295,7 @@ D1F7607623097532000C5269 /* KFImage.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = KFImage.swift; sourceTree = ""; }; D8FCF6A721C5A0E500F9ABC0 /* RedirectHandler.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RedirectHandler.swift; sourceTree = ""; }; D9638BA41C7DC71F0046523D /* ImagePrefetcherTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ImagePrefetcherTests.swift; sourceTree = ""; }; - DCEB2841257E4BE100D7A610 /* TVMonogramView+Kingfisher.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TVMonogramView+Kingfisher.swift"; sourceTree = ""; }; + E9E3ED8A2B1F66B200734CFF /* HasImageComponent+Kingfisher.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "HasImageComponent+Kingfisher.swift"; sourceTree = ""; }; F72CE9CD1FCF17ED00CC522A /* ImageModifierTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImageModifierTests.swift; sourceTree = ""; }; /* End PBXFileReference section */ @@ -396,9 +394,8 @@ D12EB83B24DD8EFC00329EE1 /* NSTextAttachment+Kingfisher.swift */, D12AB6AC215D2BB50013BA68 /* ImageView+Kingfisher.swift */, D12AB6AD215D2BB50013BA68 /* NSButton+Kingfisher.swift */, + E9E3ED8A2B1F66B200734CFF /* HasImageComponent+Kingfisher.swift */, D12AB6AE215D2BB50013BA68 /* UIButton+Kingfisher.swift */, - D12AB6AF215D2BB50013BA68 /* WKInterfaceImage+Kingfisher.swift */, - DCEB2841257E4BE100D7A610 /* TVMonogramView+Kingfisher.swift */, 22FDCE0D2700078B0044D11E /* CPListItem+Kingfisher.swift */, ); path = Extensions; @@ -832,6 +829,7 @@ D12AB6D4215D2BB50013BA68 /* Image.swift in Sources */, D1AEB09425890DE7008556DF /* ImageBinder.swift in Sources */, 4B8E2917216F3F7F0095FAD1 /* ImageDownloaderDelegate.swift in Sources */, + E9E3ED8B2B1F66B200734CFF /* HasImageComponent+Kingfisher.swift in Sources */, D1132C9725919F69003E528D /* KFOptionsSetter.swift in Sources */, D18B3222251852E100662F63 /* KF.swift in Sources */, D12AB704215D2BB50013BA68 /* Kingfisher.swift in Sources */, @@ -869,12 +867,10 @@ D1A37BDE215D34E8009B39B7 /* ImageDrawing.swift in Sources */, 4BD821672189FD330084CC21 /* SessionDataTask.swift in Sources */, D12AB708215D2BB50013BA68 /* KingfisherError.swift in Sources */, - 4BE688F822FD513700B11168 /* WKInterfaceImage+Kingfisher.swift in Sources */, D12AB724215D2BB50013BA68 /* Box.swift in Sources */, 4B8E291C216F40AA0095FAD1 /* AuthenticationChallengeResponsable.swift in Sources */, 3ADE9AF92A73CD69009A86CA /* String+SHA256.swift in Sources */, D12AB710215D2BB50013BA68 /* KingfisherOptionsInfo.swift in Sources */, - DCEB2842257E4BE100D7A610 /* TVMonogramView+Kingfisher.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/Sources/Extensions/CPListItem+Kingfisher.swift b/Sources/Extensions/CPListItem+Kingfisher.swift index 462144f25..a2bf477df 100644 --- a/Sources/Extensions/CPListItem+Kingfisher.swift +++ b/Sources/Extensions/CPListItem+Kingfisher.swift @@ -110,123 +110,39 @@ extension KingfisherWrapper where Base: CPListItem { completionHandler: (@MainActor @Sendable (Result) -> Void)? = nil) -> DownloadTask? { var mutatingSelf = self - guard let source = source else { - /** - * In iOS SDK 14.0-14.4 the image param was non-`nil`. The SDK changed in 14.5 - * to allow `nil`. The compiler version 5.4 was introduced in this same SDK, - * which allows >=14.5 SDK to set a `nil` image. This compile check allows - * newer SDK users to set the image to `nil`, while still allowing older SDK - * users to compile the framework. - */ - #if compiler(>=5.4) - self.base.setImage(placeholder) - #else - if let placeholder = placeholder { - self.base.setImage(placeholder) - } - #endif - - mutatingSelf.taskIdentifier = nil - completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) - return nil - } - - var options = parsedOptions - if !options.keepCurrentImageWhileLoading { - /** - * In iOS SDK 14.0-14.4 the image param was non-`nil`. The SDK changed in 14.5 - * to allow `nil`. The compiler version 5.4 was introduced in this same SDK, - * which allows >=14.5 SDK to set a `nil` image. This compile check allows - * newer SDK users to set the image to `nil`, while still allowing older SDK - * users to compile the framework. - */ - #if compiler(>=5.4) - self.base.setImage(placeholder) - #else // Let older SDK users deal with the older behavior. - if let placeholder = placeholder { - self.base.setImage(placeholder) - } - #endif - } - - let issuedIdentifier = Source.Identifier.next() - mutatingSelf.taskIdentifier = issuedIdentifier - - if let block = progressBlock { - options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] - } - - let task = KingfisherManager.shared.retrieveImage( + return setImage( with: source, - options: options, - downloadTaskUpdated: { task in - Task { @MainActor in mutatingSelf.imageTask = task } - }, - progressiveImageSetter: { image in - /** - * In iOS SDK 14.0-14.4 the image param was non-`nil`. The SDK changed in 14.5 - * to allow `nil`. The compiler version 5.4 was introduced in this same SDK, - * which allows >=14.5 SDK to set a `nil` image. This compile check allows - * newer SDK users to set the image to `nil`, while still allowing older SDK - * users to compile the framework. - */ - #if compiler(>=5.4) - self.base.setImage(image) - #else // Let older SDK users deal with the older behavior. - if let image = image { + imageAccessor: ImagePropertyAccessor( + setImage: { image, _ in + /** + * In iOS SDK 14.0-14.4 the image param was non-`nil`. The SDK changed in 14.5 + * to allow `nil`. The compiler version 5.4 was introduced in this same SDK, + * which allows >=14.5 SDK to set a `nil` image. This compile check allows + * newer SDK users to set the image to `nil`, while still allowing older SDK + * users to compile the framework. + */ + #if compiler(>=5.4) self.base.setImage(image) - } - #endif - }, - referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier }, - completionHandler: { result in - CallbackQueueMain.currentOrAsync { - guard issuedIdentifier == self.taskIdentifier else { - let reason: KingfisherError.ImageSettingErrorReason - do { - let value = try result.get() - reason = .notCurrentSourceTask(result: value, error: nil, source: source) - } catch { - reason = .notCurrentSourceTask(result: nil, error: error, source: source) - } - let error = KingfisherError.imageSettingError(reason: reason) - completionHandler?(.failure(error)) - return - } - - mutatingSelf.imageTask = nil - mutatingSelf.taskIdentifier = nil - - switch result { - case .success(let value): - self.base.setImage(value.image) - completionHandler?(result) - - case .failure: - if let image = options.onFailureImage { - /** - * In iOS SDK 14.0-14.4 the image param was non-`nil`. The SDK changed in 14.5 - * to allow `nil`. The compiler version 5.4 was introduced in this same SDK, - * which allows >=14.5 SDK to set a `nil` image. This compile check allows - * newer SDK users to set the image to `nil`, while still allowing older SDK - * users to compile the framework. - */ - #if compiler(>=5.4) - self.base.setImage(image) - #else // Let older SDK users deal with the older behavior. - if let unwrapped = image { - self.base.setImage(unwrapped) - } - #endif - } - completionHandler?(result) + #else + if let image = image { + self.base.setImage(image) } + #endif + }, + getImage: { + self.base.image } - } + ), + taskAccessor: TaskPropertyAccessor( + setTaskIdentifier: { mutatingSelf.taskIdentifier = $0 }, + getTaskIdentifier: { mutatingSelf.taskIdentifier }, + setTask: { mutatingSelf.imageTask = $0 } + ), + placeholder: placeholder, + parsedOptions: parsedOptions, + progressBlock: progressBlock, + completionHandler: completionHandler ) - - mutatingSelf.imageTask = task - return task } // MARK: Cancelling Image diff --git a/Sources/Extensions/HasImageComponent+Kingfisher.swift b/Sources/Extensions/HasImageComponent+Kingfisher.swift new file mode 100644 index 000000000..b36bef56e --- /dev/null +++ b/Sources/Extensions/HasImageComponent+Kingfisher.swift @@ -0,0 +1,499 @@ +// +// KingfisherHasImageComponent+Kingfisher.swift +// Kingfisher +// +// Created by JH on 2023/12/5. +// +// Copyright (c) 2023 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +public protocol KingfisherImageSettable: KingfisherCompatible { + @MainActor func setImage( + _ image: KFCrossPlatformImage?, + options: KingfisherParsedOptionsInfo + ) + @MainActor func getImage() -> KFCrossPlatformImage? +} + +public protocol KingfisherHasImageComponent: KingfisherImageSettable { + @MainActor var image: KFCrossPlatformImage? { set get } +} + +extension KingfisherHasImageComponent { + @MainActor + public func setImage(_ image: KFCrossPlatformImage?, options: KingfisherParsedOptionsInfo) { + self.image = image + } + + @MainActor + public func getImage() -> KFCrossPlatformImage? { + image + } +} + +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +@available(macOS 13.0, *) +extension NSComboButton: KingfisherHasImageComponent {} +@available(macOS 13.0, *) +extension NSColorWell: KingfisherHasImageComponent {} +extension NSTableViewRowAction: KingfisherHasImageComponent {} +extension NSMenuItem: KingfisherHasImageComponent {} +extension NSPathControlItem: KingfisherHasImageComponent {} +extension NSToolbarItem: KingfisherHasImageComponent {} +extension NSTabViewItem: KingfisherHasImageComponent {} +extension NSStatusItem: KingfisherHasImageComponent {} +extension NSCell: KingfisherHasImageComponent {} +#endif + +#if canImport(UIKit) && !os(watchOS) +import UIKit +@available(iOS 13.0, tvOS 13.0, *) +extension UIAction: KingfisherHasImageComponent {} +@available(iOS 13.0, tvOS 13.0, *) +extension UICommand: KingfisherHasImageComponent {} +extension UIBarItem: KingfisherHasImageComponent {} +#endif + +#if canImport(WatchKit) +import WatchKit +extension WKInterfaceImage: KingfisherHasImageComponent { + @MainActor public var image: KFCrossPlatformImage? { + get { nil } + set { setImage(newValue) } + } +} +#endif + +#if canImport(TVUIKit) +import TVUIKit +extension TVMonogramView: KingfisherHasImageComponent {} +#endif + +struct ImagePropertyAccessor: Sendable { + let setImage: @Sendable @MainActor (ImageType?, KingfisherParsedOptionsInfo) -> Void + let getImage: @Sendable @MainActor () -> ImageType? +} + +struct TaskPropertyAccessor: Sendable { + let setTaskIdentifier: @Sendable @MainActor (Source.Identifier.Value?) -> Void + let getTaskIdentifier: @Sendable @MainActor () -> Source.Identifier.Value? + let setTask: @Sendable @MainActor (DownloadTask?) -> Void +} + +@MainActor +extension KingfisherWrapper where Base: KingfisherImageSettable { + + // MARK: Setting Image + + /// Sets an image to the image view with a ``Source``. + /// + /// - Parameters: + /// - source: The ``Source`` object that defines data information from the network or a data provider. + /// - placeholder: A placeholder to show while retrieving the image from the given `source`. + /// - options: A set of options to define image setting behaviors. See ``KingfisherOptionsInfo`` for more. + /// - progressBlock: Called when the image downloading progress is updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieval and setting are finished. + /// - Returns: A task that represents the image downloading. + /// + /// This is the easiest way to use Kingfisher to boost the image setting process from a source. Since all parameters + /// have a default value except the `source`, you can set an image from a certain URL to an image view like this: + /// + /// ```swift + /// // Set image from a network source. + /// let url = URL(string: "https://example.com/image.png")! + /// imageView.kf.setImage(with: .network(url)) + /// + /// // Or set image from a data provider. + /// let provider = LocalFileImageDataProvider(fileURL: fileURL) + /// imageView.kf.setImage(with: .provider(provider)) + /// ``` + /// + /// For both ``Source/network(_:)`` and ``Source/provider(_:)`` sources, there are corresponding view extension + /// methods. So the code above is equivalent to: + /// + /// ```swift + /// imageView.kf.setImage(with: url) + /// imageView.kf.setImage(with: provider) + /// ``` + /// + /// Internally, this method will use ``KingfisherManager`` to get the source. Since this method will perform UI + /// changes, it is your responsibility to call it from the main thread. + /// + /// > Both `progressBlock` and `completionHandler` will also be executed in the main thread. + @discardableResult + public func setImage( + with source: Source?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: (@MainActor @Sendable (Result) -> Void)? = nil + ) -> DownloadTask? + { + let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) + return setImage( + with: source, + placeholder: placeholder, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: completionHandler + ) + } + + /// Sets an image to the image view with a ``Source``. + /// + /// - Parameters: + /// - source: The ``Source`` object that defines data information from the network or a data provider. + /// - placeholder: A placeholder to show while retrieving the image from the given `source`. + /// - options: A set of options to define image setting behaviors. See ``KingfisherOptionsInfo`` for more. + /// - completionHandler: Called when the image retrieval and setting are finished. + /// - Returns: A task that represents the image downloading. + /// + /// This is the easiest way to use Kingfisher to boost the image setting process from a source. Since all parameters + /// have a default value except the `source`, you can set an image from a certain URL to an image view like this: + /// + /// ```swift + /// // Set image from a network source. + /// let url = URL(string: "https://example.com/image.png")! + /// imageView.kf.setImage(with: .network(url)) + /// + /// // Or set image from a data provider. + /// let provider = LocalFileImageDataProvider(fileURL: fileURL) + /// imageView.kf.setImage(with: .provider(provider)) + /// ``` + /// + /// For both ``Source/network(_:)`` and ``Source/provider(_:)`` sources, there are corresponding view extension + /// methods. So the code above is equivalent to: + /// + /// ```swift + /// imageView.kf.setImage(with: url) + /// imageView.kf.setImage(with: provider) + /// ``` + /// + /// Internally, this method will use ``KingfisherManager`` to get the source. Since this method will perform UI + /// changes, it is your responsibility to call it from the main thread. + /// + /// > Both `progressBlock` and `completionHandler` will also be executed in the main thread. + @discardableResult + public func setImage( + with source: Source?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + completionHandler: (@MainActor @Sendable (Result) -> Void)? = nil + ) -> DownloadTask? + { + return setImage( + with: source, + placeholder: placeholder, + options: options, + progressBlock: nil, + completionHandler: completionHandler + ) + } + + /// Sets an image to the image view with a requested ``Resource``. + /// + /// - Parameters: + /// - resource: The ``Resource`` object contains information about the resource. + /// - placeholder: A placeholder to show while retrieving the image from the given `source`. + /// - options: A set of options to define image setting behaviors. See ``KingfisherOptionsInfo`` for more. + /// - progressBlock: Called when the image downloading progress is updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieval and setting are finished. + /// - Returns: A task that represents the image downloading. + /// + /// This is the easiest way to use Kingfisher to boost the image setting process from a source. Since all parameters + /// have a default value except the `source`, you can set an image from a certain URL to an image view like this: + /// + /// ```swift + /// // Set image from a URL resource. + /// let url = URL(string: "https://example.com/image.png")! + /// imageView.kf.setImage(with: url) + /// ``` + /// + /// Internally, this method will use ``KingfisherManager`` to get the source. Since this method will perform UI + /// changes, it is your responsibility to call it from the main thread. + /// + /// > Both `progressBlock` and `completionHandler` will also be executed in the main thread. + @discardableResult + public func setImage( + with resource: Resource?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: (@MainActor @Sendable (Result) -> Void)? = nil + ) -> DownloadTask? + { + return setImage( + with: resource?.convertToSource(), + placeholder: placeholder, + options: options, + progressBlock: progressBlock, + completionHandler: completionHandler + ) + } + + /// Sets an image to the image view with a requested ``Resource``. + /// + /// - Parameters: + /// - resource: The ``Resource`` object contains information about the resource. + /// - placeholder: A placeholder to show while retrieving the image from the given `source`. + /// - options: A set of options to define image setting behaviors. See ``KingfisherOptionsInfo`` for more. + /// - completionHandler: Called when the image retrieval and setting are finished. + /// - Returns: A task that represents the image downloading. + /// + /// This is the easiest way to use Kingfisher to boost the image setting process from a source. Since all parameters + /// have a default value except the `source`, you can set an image from a certain URL to an image view like this: + /// + /// ```swift + /// // Set image from a URL resource. + /// let url = URL(string: "https://example.com/image.png")! + /// imageView.kf.setImage(with: url) + /// ``` + /// + /// Internally, this method will use ``KingfisherManager`` to get the source. Since this method will perform UI + /// changes, it is your responsibility to call it from the main thread. + /// + /// > Both `progressBlock` and `completionHandler` will also be executed in the main thread. + @discardableResult + public func setImage( + with resource: Resource?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + completionHandler: (@MainActor @Sendable (Result) -> Void)? = nil + ) -> DownloadTask? + { + return setImage( + with: resource, + placeholder: placeholder, + options: options, + progressBlock: nil, + completionHandler: completionHandler + ) + } + + /// Sets an image to the image view with a ``ImageDataProvider``. + /// + /// - Parameters: + /// - provider: The ``ImageDataProvider`` object that defines data information from the data provider. + /// - placeholder: A placeholder to show while retrieving the image from the given `source`. + /// - options: A set of options to define image setting behaviors. See ``KingfisherOptionsInfo`` for more. + /// - progressBlock: Called when the image downloading progress is updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieval and setting are finished. + /// - Returns: A task that represents the image downloading. + /// + /// Internally, this method will use ``KingfisherManager`` to get the source. Since this method will perform UI + /// changes, it is your responsibility to call it from the main thread. + /// + /// > Both `progressBlock` and `completionHandler` will also be executed in the main thread. + @discardableResult + public func setImage( + with provider: ImageDataProvider?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: (@MainActor @Sendable (Result) -> Void)? = nil + ) -> DownloadTask? + { + return setImage( + with: provider.map { .provider($0) }, + placeholder: placeholder, + options: options, + progressBlock: progressBlock, + completionHandler: completionHandler + ) + } + + /// Sets an image to the image view with a ``ImageDataProvider``. + /// + /// - Parameters: + /// - provider: The ``ImageDataProvider`` object that defines data information from the data provider. + /// - placeholder: A placeholder to show while retrieving the image from the given `source`. + /// - options: A set of options to define image setting behaviors. See ``KingfisherOptionsInfo`` for more. + /// - completionHandler: Called when the image retrieval and setting are finished. + /// - Returns: A task that represents the image downloading. + /// + /// Internally, this method will use ``KingfisherManager`` to get the source. Since this method will perform UI + /// changes, it is your responsibility to call it from the main thread. + /// + /// > Both `progressBlock` and `completionHandler` will also be executed in the main thread. + @discardableResult + public func setImage( + with provider: ImageDataProvider?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + completionHandler: (@MainActor @Sendable (Result) -> Void)? = nil + ) -> DownloadTask? + { + return setImage( + with: provider, + placeholder: placeholder, + options: options, + progressBlock: nil, + completionHandler: completionHandler + ) + } + + func setImage( + with source: Source?, + placeholder: KFCrossPlatformImage? = nil, + parsedOptions: KingfisherParsedOptionsInfo, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: (@MainActor @Sendable (Result) -> Void)? = nil + ) -> DownloadTask? { + return setImage( + with: source, + imageAccessor: ImagePropertyAccessor( + setImage: { base.setImage($0, options: $1) }, + getImage: { base.getImage() } + ), + taskAccessor: TaskPropertyAccessor( + setTaskIdentifier: { + var mutatingSelf = self + mutatingSelf.taskIdentifier = $0 + }, + getTaskIdentifier: { self.taskIdentifier }, + setTask: { task in + var mutatingSelf = self + mutatingSelf.imageTask = task + } + ), + placeholder: placeholder, + parsedOptions: parsedOptions, + progressBlock: progressBlock, + completionHandler: completionHandler + ) + } +} + +@MainActor +extension KingfisherWrapper { + func setImage( + with source: Source?, + imageAccessor: ImagePropertyAccessor, + taskAccessor: TaskPropertyAccessor, + placeholder: KFCrossPlatformImage? = nil, + parsedOptions: KingfisherParsedOptionsInfo, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: (@MainActor @Sendable (Result) -> Void)? = nil + ) -> DownloadTask? + { + guard let source = source else { + imageAccessor.setImage(placeholder, parsedOptions) + taskAccessor.setTaskIdentifier(nil) + completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) + return nil + } + + var options = parsedOptions + + // Always set placeholder while there is no image/placeholder yet. +#if os(watchOS) + let usePlaceholderDuringLoading = !options.keepCurrentImageWhileLoading +#else + let usePlaceholderDuringLoading = !options.keepCurrentImageWhileLoading || imageAccessor.getImage() == nil +#endif + if usePlaceholderDuringLoading { + imageAccessor.setImage(placeholder, options) + } + + let issuedIdentifier = Source.Identifier.next() + taskAccessor.setTaskIdentifier(issuedIdentifier) + + if let block = progressBlock { + options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + + let task = KingfisherManager.shared.retrieveImage( + with: source, + options: options, + downloadTaskUpdated: { task in + Task { @MainActor in taskAccessor.setTask(task) } + }, + progressiveImageSetter: { imageAccessor.setImage($0, options) }, + referenceTaskIdentifierChecker: { issuedIdentifier == taskAccessor.getTaskIdentifier() }, + completionHandler: { result in + CallbackQueueMain.currentOrAsync { + guard issuedIdentifier == taskAccessor.getTaskIdentifier() else { + let reason: KingfisherError.ImageSettingErrorReason + do { + let value = try result.get() + reason = .notCurrentSourceTask(result: value, error: nil, source: source) + } catch { + reason = .notCurrentSourceTask(result: nil, error: error, source: source) + } + let error = KingfisherError.imageSettingError(reason: reason) + completionHandler?(.failure(error)) + return + } + + taskAccessor.setTask(nil) + taskAccessor.setTaskIdentifier(nil) + + switch result { + case .success(let value): + imageAccessor.setImage(value.image, options) + case .failure: + if let image = options.onFailureImage { + imageAccessor.setImage(image, options) + } + } + completionHandler?(result) + } + } + ) + taskAccessor.setTask(task) + return task + } +} + +// MARK: - Associated Object +@MainActor private var taskIdentifierKey: Void? +@MainActor private var imageTaskKey: Void? + +@MainActor +extension KingfisherWrapper where Base: KingfisherImageSettable { + + // MARK: Properties + public private(set) var taskIdentifier: Source.Identifier.Value? { + get { + let box: Box? = getAssociatedObject(base, &taskIdentifierKey) + return box?.value + } + set { + let box = newValue.map { Box($0) } + setRetainedAssociatedObject(base, &taskIdentifierKey, box) + } + } + + private var imageTask: DownloadTask? { + get { return getAssociatedObject(base, &imageTaskKey) } + set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)} + } + + /// Cancels the image download task of the image view if it is running. + /// + /// Nothing will happen if the downloading has already finished. + public func cancelDownloadTask() { + imageTask?.cancel() + } +} diff --git a/Sources/Extensions/NSButton+Kingfisher.swift b/Sources/Extensions/NSButton+Kingfisher.swift index 9970bd1ae..eb42e804d 100644 --- a/Sources/Extensions/NSButton+Kingfisher.swift +++ b/Sources/Extensions/NSButton+Kingfisher.swift @@ -108,68 +108,23 @@ extension KingfisherWrapper where Base: NSButton { ) -> DownloadTask? { var mutatingSelf = self - guard let source = source else { - base.image = placeholder - mutatingSelf.taskIdentifier = nil - completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) - return nil - } - - var options = parsedOptions - if !options.keepCurrentImageWhileLoading { - base.image = placeholder - } - - let issuedIdentifier = Source.Identifier.next() - mutatingSelf.taskIdentifier = issuedIdentifier - - if let block = progressBlock { - options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] - } - - let task = KingfisherManager.shared.retrieveImage( + return setImage( with: source, - options: options, - downloadTaskUpdated: { task in - Task { @MainActor in mutatingSelf.imageTask = task } - }, - progressiveImageSetter: { self.base.image = $0 }, - referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier }, - completionHandler: { result in - CallbackQueueMain.currentOrAsync { - guard issuedIdentifier == self.taskIdentifier else { - let reason: KingfisherError.ImageSettingErrorReason - do { - let value = try result.get() - reason = .notCurrentSourceTask(result: value, error: nil, source: source) - } catch { - reason = .notCurrentSourceTask(result: nil, error: error, source: source) - } - let error = KingfisherError.imageSettingError(reason: reason) - completionHandler?(.failure(error)) - return - } - - mutatingSelf.imageTask = nil - mutatingSelf.taskIdentifier = nil - - switch result { - case .success(let value): - self.base.image = value.image - completionHandler?(result) - - case .failure: - if let image = options.onFailureImage { - self.base.image = image - } - completionHandler?(result) - } - } - } + imageAccessor: ImagePropertyAccessor( + setImage: { image, _ in + base.image = image + }, getImage: { + base.image + }), + taskAccessor: TaskPropertyAccessor( + setTaskIdentifier: { mutatingSelf.taskIdentifier = $0 }, + getTaskIdentifier: { mutatingSelf.taskIdentifier }, + setTask: { mutatingSelf.imageTask = $0 }), + placeholder: placeholder, + parsedOptions: parsedOptions, + progressBlock: progressBlock, + completionHandler: completionHandler ) - - mutatingSelf.imageTask = task - return task } // MARK: Cancelling Downloading Task @@ -242,76 +197,24 @@ extension KingfisherWrapper where Base: NSButton { ) -> DownloadTask? { var mutatingSelf = self - guard let source = source else { - base.alternateImage = placeholder - mutatingSelf.alternateTaskIdentifier = nil - completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) - return nil - } - - var options = parsedOptions - if !options.keepCurrentImageWhileLoading { - base.alternateImage = placeholder - } - - let issuedIdentifier = Source.Identifier.next() - mutatingSelf.alternateTaskIdentifier = issuedIdentifier - - if let block = progressBlock { - options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] - } - - if let provider = ImageProgressiveProvider(options: options, refresh: { image in - self.base.alternateImage = image - }) { - options.onDataReceived = (options.onDataReceived ?? []) + [provider] - } - - options.onDataReceived?.forEach { - $0.onShouldApply = { issuedIdentifier == self.alternateTaskIdentifier } - } - - let task = KingfisherManager.shared.retrieveImage( + return setImage( with: source, - options: options, - downloadTaskUpdated: { task in - Task { @MainActor in mutatingSelf.alternateImageTask = task } - }, - completionHandler: { result in - CallbackQueueMain.currentOrAsync { - guard issuedIdentifier == self.alternateTaskIdentifier else { - let reason: KingfisherError.ImageSettingErrorReason - do { - let value = try result.get() - reason = .notCurrentSourceTask(result: value, error: nil, source: source) - } catch { - reason = .notCurrentSourceTask(result: nil, error: error, source: source) - } - let error = KingfisherError.imageSettingError(reason: reason) - completionHandler?(.failure(error)) - return - } - - mutatingSelf.alternateImageTask = nil - mutatingSelf.alternateTaskIdentifier = nil - - switch result { - case .success(let value): - self.base.alternateImage = value.image - completionHandler?(result) - - case .failure: - if let image = options.onFailureImage { - self.base.alternateImage = image - } - completionHandler?(result) - } - } - } + imageAccessor: ImagePropertyAccessor( + setImage: { image, _ in + base.alternateImage = image + }, getImage: { + base.alternateImage + }), + taskAccessor: TaskPropertyAccessor( + setTaskIdentifier: { mutatingSelf.alternateTaskIdentifier = $0 }, + getTaskIdentifier: { mutatingSelf.alternateTaskIdentifier }, + setTask: { mutatingSelf.alternateImageTask = $0 } + ), + placeholder: placeholder, + parsedOptions: parsedOptions, + progressBlock: progressBlock, + completionHandler: completionHandler ) - - mutatingSelf.alternateImageTask = task - return task } // MARK: Cancelling Alternate Image Downloading Task diff --git a/Sources/Extensions/TVMonogramView+Kingfisher.swift b/Sources/Extensions/TVMonogramView+Kingfisher.swift deleted file mode 100644 index da3738614..000000000 --- a/Sources/Extensions/TVMonogramView+Kingfisher.swift +++ /dev/null @@ -1,216 +0,0 @@ -// -// TVMonogramView+Kingfisher.swift -// Kingfisher -// -// Created by Marvin Nazari on 2020-12-07. -// -// Copyright (c) 2020 Wei Wang -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation - -#if canImport(TVUIKit) - -import TVUIKit - -@MainActor -@available(tvOS 12.0, *) -extension KingfisherWrapper where Base: TVMonogramView { - - // MARK: Setting Image - - /// Sets an image to the image view with a source. - /// - /// - Parameters: - /// - source: The `Source` object contains information about the image. - /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. - /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. - /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an - /// `expectedContentLength`, this block will not be called. - /// - completionHandler: Called when the image retrieved and set finished. - /// - Returns: A task represents the image downloading. - /// - /// - Note: - /// - /// Internally, this method will use `KingfisherManager` to get the requested source - /// Since this method will perform UI changes, you must call it from the main thread. - /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. - /// - @discardableResult - public func setImage( - with source: Source?, - placeholder: KFCrossPlatformImage? = nil, - options: KingfisherOptionsInfo? = nil, - progressBlock: DownloadProgressBlock? = nil, - completionHandler: (@MainActor @Sendable (Result) -> Void)? = nil - ) -> DownloadTask? - { - let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) - return setImage( - with: source, - placeholder: placeholder, - parsedOptions: options, - progressBlock: progressBlock, - completionHandler: completionHandler - ) - } - - func setImage( - with source: Source?, - placeholder: KFCrossPlatformImage? = nil, - parsedOptions: KingfisherParsedOptionsInfo, - progressBlock: DownloadProgressBlock? = nil, - completionHandler: (@MainActor @Sendable (Result) -> Void)? = nil - ) -> DownloadTask? - { - var mutatingSelf = self - guard let source = source else { - base.image = placeholder - mutatingSelf.taskIdentifier = nil - completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) - return nil - } - - var options = parsedOptions - if !options.keepCurrentImageWhileLoading { - base.image = placeholder - } - - let issuedIdentifier = Source.Identifier.next() - mutatingSelf.taskIdentifier = issuedIdentifier - - if let block = progressBlock { - options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] - } - - let task = KingfisherManager.shared.retrieveImage( - with: source, - options: options, - downloadTaskUpdated: { task in - Task { @MainActor in mutatingSelf.imageTask = task } - }, - progressiveImageSetter: { self.base.image = $0 }, - referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier }, - completionHandler: { result in - CallbackQueueMain.currentOrAsync { - guard issuedIdentifier == self.taskIdentifier else { - let reason: KingfisherError.ImageSettingErrorReason - do { - let value = try result.get() - reason = .notCurrentSourceTask(result: value, error: nil, source: source) - } catch { - reason = .notCurrentSourceTask(result: nil, error: error, source: source) - } - let error = KingfisherError.imageSettingError(reason: reason) - completionHandler?(.failure(error)) - return - } - - mutatingSelf.imageTask = nil - mutatingSelf.taskIdentifier = nil - - switch result { - case .success(let value): - self.base.image = value.image - completionHandler?(result) - - case .failure: - if let image = options.onFailureImage { - self.base.image = image - } - completionHandler?(result) - } - } - } - ) - - mutatingSelf.imageTask = task - return task - } - - /// Sets an image to the image view with a requested resource. - /// - /// - Parameters: - /// - resource: The `Resource` object contains information about the image. - /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. - /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. - /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an - /// `expectedContentLength`, this block will not be called. - /// - completionHandler: Called when the image retrieved and set finished. - /// - Returns: A task represents the image downloading. - /// - /// - Note: - /// - /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache - /// or network. Since this method will perform UI changes, you must call it from the main thread. - /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. - /// - @discardableResult - public func setImage( - with resource: Resource?, - placeholder: KFCrossPlatformImage? = nil, - options: KingfisherOptionsInfo? = nil, - progressBlock: DownloadProgressBlock? = nil, - completionHandler: (@MainActor @Sendable (Result) -> Void)? = nil - ) -> DownloadTask? - { - return setImage( - with: resource?.convertToSource(), - placeholder: placeholder, - options: options, - progressBlock: progressBlock, - completionHandler: completionHandler) - } - - // MARK: Cancelling Image - - /// Cancel the image download task bounded to the image view if it is running. - /// Nothing will happen if the downloading has already finished. - public func cancelDownloadTask() { - imageTask?.cancel() - } -} - -@MainActor private var taskIdentifierKey: Void? -@MainActor private var imageTaskKey: Void? - -// MARK: Properties -@MainActor -@available(tvOS 12.0, *) -extension KingfisherWrapper where Base: TVMonogramView { - - public private(set) var taskIdentifier: Source.Identifier.Value? { - get { - let box: Box? = getAssociatedObject(base, &taskIdentifierKey) - return box?.value - } - set { - let box = newValue.map { Box($0) } - setRetainedAssociatedObject(base, &taskIdentifierKey, box) - } - } - - private var imageTask: DownloadTask? { - get { return getAssociatedObject(base, &imageTaskKey) } - set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)} - } -} - -#endif diff --git a/Sources/Extensions/UIButton+Kingfisher.swift b/Sources/Extensions/UIButton+Kingfisher.swift index 703a9298c..d43d9a3a1 100644 --- a/Sources/Extensions/UIButton+Kingfisher.swift +++ b/Sources/Extensions/UIButton+Kingfisher.swift @@ -114,69 +114,23 @@ extension KingfisherWrapper where Base: UIButton { progressBlock: DownloadProgressBlock? = nil, completionHandler: (@MainActor @Sendable (Result) -> Void)? = nil) -> DownloadTask? { - guard let source = source else { - base.setImage(placeholder, for: state) - setTaskIdentifier(nil, for: state) - completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) - return nil - } - - var options = parsedOptions - if !options.keepCurrentImageWhileLoading { - base.setImage(placeholder, for: state) - } - var mutatingSelf = self - let issuedIdentifier = Source.Identifier.next() - setTaskIdentifier(issuedIdentifier, for: state) - - if let block = progressBlock { - options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] - } - - let task = KingfisherManager.shared.retrieveImage( + return setImage( with: source, - options: options, - downloadTaskUpdated: { task in - Task { @MainActor in mutatingSelf.imageTask = task } - }, - progressiveImageSetter: { self.base.setImage($0, for: state) }, - referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier(for: state) }, - completionHandler: { result in - CallbackQueueMain.currentOrAsync { - guard issuedIdentifier == self.taskIdentifier(for: state) else { - let reason: KingfisherError.ImageSettingErrorReason - do { - let value = try result.get() - reason = .notCurrentSourceTask(result: value, error: nil, source: source) - } catch { - reason = .notCurrentSourceTask(result: nil, error: error, source: source) - } - let error = KingfisherError.imageSettingError(reason: reason) - completionHandler?(.failure(error)) - return - } - - mutatingSelf.imageTask = nil - mutatingSelf.setTaskIdentifier(nil, for: state) - - switch result { - case .success(let value): - self.base.setImage(value.image, for: state) - completionHandler?(result) - - case .failure: - if let image = options.onFailureImage { - self.base.setImage(image, for: state) - } - completionHandler?(result) - } - } - } + imageAccessor: ImagePropertyAccessor( + setImage: { image, _ in base.setImage(image, for: state) }, + getImage: { base.image(for: state) } + ), + taskAccessor: TaskPropertyAccessor( + setTaskIdentifier: { setTaskIdentifier($0, for: state) }, + getTaskIdentifier: { taskIdentifier(for: state) }, + setTask: { mutatingSelf.imageTask = $0 } + ), + placeholder: placeholder, + parsedOptions: parsedOptions, + progressBlock: progressBlock, + completionHandler: completionHandler ) - - mutatingSelf.imageTask = task - return task } // MARK: Cancelling Downloading Task @@ -269,71 +223,27 @@ extension KingfisherWrapper where Base: UIButton { progressBlock: DownloadProgressBlock? = nil, completionHandler: (@MainActor @Sendable (Result) -> Void)? = nil) -> DownloadTask? { - guard let source = source else { - base.setBackgroundImage(placeholder, for: state) - setBackgroundTaskIdentifier(nil, for: state) - completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) - return nil - } - - var options = parsedOptions - if !options.keepCurrentImageWhileLoading { - base.setBackgroundImage(placeholder, for: state) - } - var mutatingSelf = self - let issuedIdentifier = Source.Identifier.next() - setBackgroundTaskIdentifier(issuedIdentifier, for: state) - - if let block = progressBlock { - options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] - } - - let task = KingfisherManager.shared.retrieveImage( + return setImage( with: source, - options: options, - downloadTaskUpdated: { task in - Task { @MainActor in - mutatingSelf.backgroundImageTask = task - } - }, - progressiveImageSetter: { self.base.setBackgroundImage($0, for: state) }, - referenceTaskIdentifierChecker: { issuedIdentifier == self.backgroundTaskIdentifier(for: state) }, - completionHandler: { result in - CallbackQueueMain.currentOrAsync { - guard issuedIdentifier == self.backgroundTaskIdentifier(for: state) else { - let reason: KingfisherError.ImageSettingErrorReason - do { - let value = try result.get() - reason = .notCurrentSourceTask(result: value, error: nil, source: source) - } catch { - reason = .notCurrentSourceTask(result: nil, error: error, source: source) - } - let error = KingfisherError.imageSettingError(reason: reason) - completionHandler?(.failure(error)) - return - } - - mutatingSelf.backgroundImageTask = nil - mutatingSelf.setBackgroundTaskIdentifier(nil, for: state) - - switch result { - case .success(let value): - self.base.setBackgroundImage(value.image, for: state) - completionHandler?(result) - - case .failure: - if let image = options.onFailureImage { - self.base.setBackgroundImage(image, for: state) - } - completionHandler?(result) - } + imageAccessor: ImagePropertyAccessor( + setImage: { image, _ in + base.setBackgroundImage(image, for: state) + }, + getImage: { + base.backgroundImage(for: state) } - } + ), + taskAccessor: TaskPropertyAccessor( + setTaskIdentifier: { setBackgroundTaskIdentifier($0, for: state) }, + getTaskIdentifier: { backgroundTaskIdentifier(for: state) }, + setTask: { mutatingSelf.backgroundImageTask = $0 } + ), + placeholder: placeholder, + parsedOptions: parsedOptions, + progressBlock: progressBlock, + completionHandler: completionHandler ) - - mutatingSelf.backgroundImageTask = task - return task } // MARK: Cancelling Background Downloading Task diff --git a/Sources/Extensions/WKInterfaceImage+Kingfisher.swift b/Sources/Extensions/WKInterfaceImage+Kingfisher.swift deleted file mode 100644 index 5a6f7f1bf..000000000 --- a/Sources/Extensions/WKInterfaceImage+Kingfisher.swift +++ /dev/null @@ -1,208 +0,0 @@ -// -// WKInterfaceImage+Kingfisher.swift -// Kingfisher -// -// Created by Rodrigo Borges Soares on 04/05/18. -// -// Copyright (c) 2019 Wei Wang -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if canImport(WatchKit) - -import WatchKit - -@MainActor -extension KingfisherWrapper where Base: WKInterfaceImage { - - // MARK: Setting Image - - /// Sets an image to the image view with a source. - /// - /// - Parameters: - /// - source: The `Source` object contains information about the image. - /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. - /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. - /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an - /// `expectedContentLength`, this block will not be called. - /// - completionHandler: Called when the image retrieved and set finished. - /// - Returns: A task represents the image downloading. - /// - /// - Note: - /// - /// Internally, this method will use `KingfisherManager` to get the requested source - /// Since this method will perform UI changes, you must call it from the main thread. - /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. - /// - @discardableResult - public func setImage( - with source: Source?, - placeholder: KFCrossPlatformImage? = nil, - options: KingfisherOptionsInfo? = nil, - progressBlock: DownloadProgressBlock? = nil, - completionHandler: (@Sendable (Result) -> Void)? = nil) -> DownloadTask? - { - let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) - return setImage( - with: source, - placeholder: placeholder, - parsedOptions: options, - progressBlock: progressBlock, - completionHandler: completionHandler - ) - } - - /// Sets an image to the image view with a requested resource. - /// - /// - Parameters: - /// - resource: The `Resource` object contains information about the image. - /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. - /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. - /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an - /// `expectedContentLength`, this block will not be called. - /// - completionHandler: Called when the image retrieved and set finished. - /// - Returns: A task represents the image downloading. - /// - /// - Note: - /// - /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache - /// or network. Since this method will perform UI changes, you must call it from the main thread. - /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. - /// - @discardableResult - public func setImage( - with resource: Resource?, - placeholder: KFCrossPlatformImage? = nil, - options: KingfisherOptionsInfo? = nil, - progressBlock: DownloadProgressBlock? = nil, - completionHandler: (@Sendable (Result) -> Void)? = nil) -> DownloadTask? - { - return setImage( - with: resource?.convertToSource(), - placeholder: placeholder, - options: options, - progressBlock: progressBlock, - completionHandler: completionHandler) - } - - func setImage( - with source: Source?, - placeholder: KFCrossPlatformImage? = nil, - parsedOptions: KingfisherParsedOptionsInfo, - progressBlock: DownloadProgressBlock? = nil, - completionHandler: (@Sendable (Result) -> Void)? = nil) -> DownloadTask? - { - var mutatingSelf = self - guard let source = source else { - base.setImage(placeholder) - mutatingSelf.taskIdentifier = nil - completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) - return nil - } - - var options = parsedOptions - if !options.keepCurrentImageWhileLoading { - base.setImage(placeholder) - } - - let issuedIdentifier = Source.Identifier.next() - mutatingSelf.taskIdentifier = issuedIdentifier - - if let block = progressBlock { - options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] - } - - let task = KingfisherManager.shared.retrieveImage( - with: source, - options: options, - downloadTaskUpdated: { task in - Task { @MainActor in mutatingSelf.imageTask = task } - }, - progressiveImageSetter: { self.base.setImage($0) }, - referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier }, - completionHandler: { result in - CallbackQueueMain.currentOrAsync { - guard issuedIdentifier == self.taskIdentifier else { - let reason: KingfisherError.ImageSettingErrorReason - do { - let value = try result.get() - reason = .notCurrentSourceTask(result: value, error: nil, source: source) - } catch { - reason = .notCurrentSourceTask(result: nil, error: error, source: source) - } - let error = KingfisherError.imageSettingError(reason: reason) - completionHandler?(.failure(error)) - return - } - - mutatingSelf.imageTask = nil - mutatingSelf.taskIdentifier = nil - - switch result { - case .success(let value): - self.base.setImage(value.image) - completionHandler?(result) - - case .failure: - if let image = options.onFailureImage { - self.base.setImage(image) - } - completionHandler?(result) - } - } - } - ) - - mutatingSelf.imageTask = task - return task - } - - // MARK: Cancelling Image - - /// Cancel the image download task bounded to the image view if it is running. - /// Nothing will happen if the downloading has already finished. - public func cancelDownloadTask() { - imageTask?.cancel() - } -} - -@MainActor private var taskIdentifierKey: Void? -@MainActor private var imageTaskKey: Void? - -// MARK: Properties -@MainActor -extension KingfisherWrapper where Base: WKInterfaceImage { - - public private(set) var taskIdentifier: Source.Identifier.Value? { - get { - let box: Box? = getAssociatedObject(base, &taskIdentifierKey) - return box?.value - } - set { - let box = newValue.map { Box($0) } - setRetainedAssociatedObject(base, &taskIdentifierKey, box) - } - } - - private var imageTask: DownloadTask? { - get { return getAssociatedObject(base, &imageTaskKey) } - set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)} - } -} -#endif diff --git a/Sources/Image/Placeholder.swift b/Sources/Image/Placeholder.swift index 9202e152a..f45862f56 100644 --- a/Sources/Image/Placeholder.swift +++ b/Sources/Image/Placeholder.swift @@ -55,6 +55,7 @@ public protocol Placeholder { @MainActor func remove(from imageView: KFCrossPlatformImageView) } +@MainActor extension KFCrossPlatformImage: Placeholder { public func add(to imageView: KFCrossPlatformImageView) { imageView.image = self @@ -63,6 +64,14 @@ extension KFCrossPlatformImage: Placeholder { public func remove(from imageView: KFCrossPlatformImageView) { imageView.image = nil } + + public func add(to base: any KingfisherHasImageComponent) { + base.image = self + } + + public func remove(from base: any KingfisherHasImageComponent) { + base.image = nil + } } /// Default implementation of an arbitrary view as a placeholder. The view will be diff --git a/Tests/KingfisherTests/ImageViewExtensionTests.swift b/Tests/KingfisherTests/ImageViewExtensionTests.swift index fff3b21da..04d99de4a 100644 --- a/Tests/KingfisherTests/ImageViewExtensionTests.swift +++ b/Tests/KingfisherTests/ImageViewExtensionTests.swift @@ -420,13 +420,20 @@ class ImageViewExtensionTests: XCTestCase { @MainActor func testSettingImageKeepingRespectingPlaceholder() { let exp = expectation(description: #function) - let url = testURLs[0] - stub(url, data: testImageData) - + // While current image is nil, set placeholder - imageView.kf.setImage(with: url, placeholder: testImage, options: [.keepCurrentImageWhileLoading]) { result in } - XCTAssertNotNil(imageView.image) + let url = testURLs[0] + imageView.kf.setImage(with: url, placeholder: testImage, options: [.keepCurrentImageWhileLoading]) { result in + exp.fulfill() + } XCTAssertEqual(testImage, imageView.image) + waitForExpectations(timeout: 3, handler: nil) + } + + @MainActor func testMe() { + let exp = expectation(description: #function) + let url = testURLs[0] + stub(url, data: testImageData) // While current image is not nil, keep it let anotherImage = KFCrossPlatformImage(data: testImageJEPGData) @@ -435,7 +442,6 @@ class ImageViewExtensionTests: XCTestCase { XCTAssertNotEqual(self.imageView.image, anotherImage) exp.fulfill() } - XCTAssertNotNil(imageView.image) XCTAssertEqual(anotherImage, imageView.image) waitForExpectations(timeout: 3, handler: nil)