NSTextAttachment+Kingfisher.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. //
  2. // NSTextAttachment+Kingfisher.swift
  3. // Kingfisher
  4. //
  5. // Created by Benjamin Briggs on 22/07/2019.
  6. //
  7. // Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. #if !os(watchOS)
  27. #if os(macOS)
  28. import AppKit
  29. #else
  30. import UIKit
  31. #endif
  32. @MainActor
  33. extension KingfisherWrapper where Base: NSTextAttachment {
  34. // MARK: Setting Image
  35. /// Sets an image to the text attachment with a source.
  36. ///
  37. /// - Parameters:
  38. /// - source: The ``Source`` object that defines data information from the network or a data provider.
  39. /// - attributedView: The owner of the attributed string to which this `NSTextAttachment` is added.
  40. /// - placeholder: A placeholder to show while retrieving the image from the given `source`.
  41. /// - options: A set of options to define image setting behaviors. See ``KingfisherOptionsInfo`` for more.
  42. /// - progressBlock: Called when the image downloading progress is updated. If the response does not contain an
  43. /// `expectedContentLength`, this block will not be called.
  44. /// - completionHandler: Called when the image retrieval and setting are finished.
  45. /// - Returns: A task that represents the image downloading.
  46. ///
  47. /// Internally, this method will use ``KingfisherManager`` to get the requested source. Since this method will
  48. /// perform UI changes, it is your responsibility of calling it from the main thread.
  49. ///
  50. /// The retrieved image will be set to the `NSTextAttachment.image` property. Because it is not an image view-based
  51. /// rendering, options related to the view, such as ``KingfisherOptionsInfoItem/transition(_:)``, are not supported.
  52. ///
  53. /// Kingfisher will call `setNeedsDisplay` on the `attributedView` when the image task is done. It gives the view a
  54. /// chance to render the attributed string again for displaying the downloaded image. For example, if you set an
  55. /// attributed string with this `NSTextAttachment` to a `UILabel` object, pass it as the `attributedView` parameter.
  56. ///
  57. /// Here is a typical use case:
  58. ///
  59. /// ```swift
  60. /// let label: UILabel = // ...
  61. ///
  62. /// let textAttachment = NSTextAttachment()
  63. /// textAttachment.kf.setImage(
  64. /// with: URL(string: "https://onevcat.com/assets/images/avatar.jpg")!,
  65. /// attributedView: label,
  66. /// options: [
  67. /// .processor(
  68. /// ResizingImageProcessor(referenceSize: .init(width: 30, height: 30))
  69. /// |> RoundCornerImageProcessor(cornerRadius: 15))
  70. /// ]
  71. /// )
  72. ///
  73. /// let attributedText = NSMutableAttributedString(string: "Hello World")
  74. /// attributedText.replaceCharacters(in: NSRange(), with: NSAttributedString(attachment: textAttachment))
  75. /// label.attributedText = attributedText
  76. /// ```
  77. @discardableResult
  78. public func setImage(
  79. with source: Source?,
  80. attributedView: @autoclosure @escaping @Sendable () -> KFCrossPlatformView,
  81. placeholder: KFCrossPlatformImage? = nil,
  82. options: KingfisherOptionsInfo? = nil,
  83. progressBlock: DownloadProgressBlock? = nil,
  84. completionHandler: (@MainActor @Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil
  85. ) -> DownloadTask?
  86. {
  87. let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
  88. return setImage(
  89. with: source,
  90. attributedView: attributedView,
  91. placeholder: placeholder,
  92. parsedOptions: options,
  93. progressBlock: progressBlock,
  94. completionHandler: completionHandler
  95. )
  96. }
  97. /// Sets an image to the text attachment with a source.
  98. ///
  99. /// - Parameters:
  100. /// - resource: The ``Resource`` object that defines data information from the network or a data provider.
  101. /// - attributedView: The owner of the attributed string to which this `NSTextAttachment` is added.
  102. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  103. /// - options: A set of options to define image setting behaviors. See ``KingfisherOptionsInfo`` for more.
  104. /// - progressBlock: Called when the image downloading progress is updated. If the response does not contain an
  105. /// `expectedContentLength`, this block will not be called.
  106. /// - completionHandler: Called when the image retrieval and setting are finished.
  107. /// - Returns: A task that represents the image downloading.
  108. ///
  109. /// Internally, this method will use ``KingfisherManager`` to get the requested source. Since this method will
  110. /// perform UI changes, it is your responsibility of calling it from the main thread.
  111. ///
  112. /// The retrieved image will be set to the `NSTextAttachment.image` property. Because it is not an image view-based
  113. /// rendering, options related to the view, such as ``KingfisherOptionsInfoItem/transition(_:)``, are not supported.
  114. ///
  115. /// Kingfisher will call `setNeedsDisplay` on the `attributedView` when the image task is done. It gives the view a
  116. /// chance to render the attributed string again for displaying the downloaded image. For example, if you set an
  117. /// attributed string with this `NSTextAttachment` to a `UILabel` object, pass it as the `attributedView` parameter.
  118. ///
  119. /// Here is a typical use case:
  120. ///
  121. /// ```swift
  122. /// let label: UILabel = // ...
  123. ///
  124. /// let textAttachment = NSTextAttachment()
  125. /// textAttachment.kf.setImage(
  126. /// with: URL(string: "https://onevcat.com/assets/images/avatar.jpg")!,
  127. /// attributedView: label,
  128. /// options: [
  129. /// .processor(
  130. /// ResizingImageProcessor(referenceSize: .init(width: 30, height: 30))
  131. /// |> RoundCornerImageProcessor(cornerRadius: 15))
  132. /// ]
  133. /// )
  134. ///
  135. /// let attributedText = NSMutableAttributedString(string: "Hello World")
  136. /// attributedText.replaceCharacters(in: NSRange(), with: NSAttributedString(attachment: textAttachment))
  137. /// label.attributedText = attributedText
  138. /// ```
  139. @discardableResult
  140. public func setImage(
  141. with resource: (any Resource)?,
  142. attributedView: @autoclosure @escaping @Sendable () -> KFCrossPlatformView,
  143. placeholder: KFCrossPlatformImage? = nil,
  144. options: KingfisherOptionsInfo? = nil,
  145. progressBlock: DownloadProgressBlock? = nil,
  146. completionHandler: (@MainActor @Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil
  147. ) -> DownloadTask?
  148. {
  149. let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
  150. return setImage(
  151. with: resource.map { .network($0) },
  152. attributedView: attributedView,
  153. placeholder: placeholder,
  154. parsedOptions: options,
  155. progressBlock: progressBlock,
  156. completionHandler: completionHandler
  157. )
  158. }
  159. func setImage(
  160. with source: Source?,
  161. attributedView: @escaping @Sendable () -> KFCrossPlatformView,
  162. placeholder: KFCrossPlatformImage? = nil,
  163. parsedOptions: KingfisherParsedOptionsInfo,
  164. progressBlock: DownloadProgressBlock? = nil,
  165. completionHandler: (@MainActor @Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil
  166. ) -> DownloadTask?
  167. {
  168. var mutatingSelf = self
  169. guard let source = source else {
  170. base.image = placeholder
  171. mutatingSelf.taskIdentifier = nil
  172. completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
  173. return nil
  174. }
  175. var options = parsedOptions
  176. if !options.keepCurrentImageWhileLoading {
  177. base.image = placeholder
  178. }
  179. let issuedIdentifier = Source.Identifier.next()
  180. mutatingSelf.taskIdentifier = issuedIdentifier
  181. if let block = progressBlock {
  182. options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
  183. }
  184. let task = KingfisherManager.shared.retrieveImage(
  185. with: source,
  186. options: options,
  187. progressiveImageSetter: { self.base.image = $0 },
  188. referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier },
  189. completionHandler: { result in
  190. CallbackQueueMain.currentOrAsync {
  191. guard issuedIdentifier == self.taskIdentifier else {
  192. let reason: KingfisherError.ImageSettingErrorReason
  193. do {
  194. let value = try result.get()
  195. reason = .notCurrentSourceTask(result: value, error: nil, source: source)
  196. } catch {
  197. reason = .notCurrentSourceTask(result: nil, error: error, source: source)
  198. }
  199. let error = KingfisherError.imageSettingError(reason: reason)
  200. completionHandler?(.failure(error))
  201. return
  202. }
  203. mutatingSelf.imageTask = nil
  204. mutatingSelf.taskIdentifier = nil
  205. switch result {
  206. case .success(let value):
  207. self.base.image = value.image
  208. let view = attributedView()
  209. #if canImport(UIKit)
  210. view.setNeedsDisplay()
  211. #else
  212. view.setNeedsDisplay(view.bounds)
  213. #endif
  214. case .failure:
  215. if let image = options.onFailureImage {
  216. self.base.image = image
  217. }
  218. }
  219. completionHandler?(result)
  220. }
  221. }
  222. )
  223. mutatingSelf.imageTask = task
  224. return task
  225. }
  226. // MARK: Cancelling Image
  227. /// Cancel the image download task bound to the text attachment if it is running.
  228. ///
  229. /// Nothing will happen if the downloading has already finished.
  230. public func cancelDownloadTask() {
  231. imageTask?.cancel()
  232. }
  233. }
  234. @MainActor private var taskIdentifierKey: Void?
  235. @MainActor private var imageTaskKey: Void?
  236. // MARK: Properties
  237. @MainActor
  238. extension KingfisherWrapper where Base: NSTextAttachment {
  239. public private(set) var taskIdentifier: Source.Identifier.Value? {
  240. get {
  241. let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
  242. return box?.value
  243. }
  244. set {
  245. let box = newValue.map { Box($0) }
  246. setRetainedAssociatedObject(base, &taskIdentifierKey, box)
  247. }
  248. }
  249. private var imageTask: DownloadTask? {
  250. get { return getAssociatedObject(base, &imageTaskKey) }
  251. set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
  252. }
  253. }
  254. #endif