NSTextAttachment+Kingfisher.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. extension KingfisherWrapper where Base: NSTextAttachment {
  33. // MARK: Setting Image
  34. /// Sets an image to the text attachment with a source.
  35. ///
  36. /// - Parameters:
  37. /// - source: The `Source` object defines data information from network or a data provider.
  38. /// - attributedView: The owner of the attributed string which this `NSTextAttachment` is added.
  39. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  40. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  41. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  42. /// `expectedContentLength`, this block will not be called.
  43. /// - completionHandler: Called when the image retrieved and set finished.
  44. /// - Returns: A task represents the image downloading.
  45. ///
  46. /// - Note:
  47. ///
  48. /// Internally, this method will use `KingfisherManager` to get the requested source
  49. /// Since this method will perform UI changes, you must call it from the main thread.
  50. ///
  51. /// The retrieved image will be set to `NSTextAttachment.image` property. Because it is not an image view based
  52. /// rendering, options related to view, such as `.transition`, are not supported.
  53. ///
  54. /// Kingfisher will call `setNeedsDisplay` on the `attributedView` when the image task done. It gives the view a
  55. /// chance to render the attributed string again for displaying the downloaded image. For example, if you set an
  56. /// attributed with this `NSTextAttachment` to a `UILabel` object, pass it as the `attributedView` parameter.
  57. ///
  58. /// Here is a typical use case:
  59. ///
  60. /// ```swift
  61. /// let attributedText = NSMutableAttributedString(string: "Hello World")
  62. /// let textAttachment = NSTextAttachment()
  63. ///
  64. /// textAttachment.kf.setImage(
  65. /// with: URL(string: "https://onevcat.com/assets/images/avatar.jpg")!,
  66. /// attributedView: label,
  67. /// options: [
  68. /// .processor(
  69. /// ResizingImageProcessor(referenceSize: .init(width: 30, height: 30))
  70. /// |> RoundCornerImageProcessor(cornerRadius: 15))
  71. /// ]
  72. /// )
  73. /// attributedText.replaceCharacters(in: NSRange(), with: NSAttributedString(attachment: textAttachment))
  74. /// label.attributedText = attributedText
  75. /// ```
  76. ///
  77. @discardableResult
  78. public func setImage(
  79. with source: Source?,
  80. attributedView: @autoclosure @escaping () -> KFCrossPlatformView,
  81. placeholder: KFCrossPlatformImage? = nil,
  82. options: KingfisherOptionsInfo? = nil,
  83. progressBlock: DownloadProgressBlock? = nil,
  84. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  85. {
  86. let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
  87. return setImage(
  88. with: source,
  89. attributedView: attributedView,
  90. placeholder: placeholder,
  91. parsedOptions: options,
  92. progressBlock: progressBlock,
  93. completionHandler: completionHandler
  94. )
  95. }
  96. /// Sets an image to the text attachment with a source.
  97. ///
  98. /// - Parameters:
  99. /// - resource: The `Resource` object contains information about the resource.
  100. /// - attributedView: The owner of the attributed string which this `NSTextAttachment` is added.
  101. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  102. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  103. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  104. /// `expectedContentLength`, this block will not be called.
  105. /// - completionHandler: Called when the image retrieved and set finished.
  106. /// - Returns: A task represents the image downloading.
  107. ///
  108. /// - Note:
  109. ///
  110. /// Internally, this method will use `KingfisherManager` to get the requested source
  111. /// Since this method will perform UI changes, you must call it from the main thread.
  112. ///
  113. /// The retrieved image will be set to `NSTextAttachment.image` property. Because it is not an image view based
  114. /// rendering, options related to view, such as `.transition`, are not supported.
  115. ///
  116. /// Kingfisher will call `setNeedsDisplay` on the `attributedView` when the image task done. It gives the view a
  117. /// chance to render the attributed string again for displaying the downloaded image. For example, if you set an
  118. /// attributed with this `NSTextAttachment` to a `UILabel` object, pass it as the `attributedView` parameter.
  119. ///
  120. /// Here is a typical use case:
  121. ///
  122. /// ```swift
  123. /// let attributedText = NSMutableAttributedString(string: "Hello World")
  124. /// let textAttachment = NSTextAttachment()
  125. ///
  126. /// textAttachment.kf.setImage(
  127. /// with: URL(string: "https://onevcat.com/assets/images/avatar.jpg")!,
  128. /// attributedView: label,
  129. /// options: [
  130. /// .processor(
  131. /// ResizingImageProcessor(referenceSize: .init(width: 30, height: 30))
  132. /// |> RoundCornerImageProcessor(cornerRadius: 15))
  133. /// ]
  134. /// )
  135. /// attributedText.replaceCharacters(in: NSRange(), with: NSAttributedString(attachment: textAttachment))
  136. /// label.attributedText = attributedText
  137. /// ```
  138. ///
  139. @discardableResult
  140. public func setImage(
  141. with resource: Resource?,
  142. attributedView: @autoclosure @escaping () -> KFCrossPlatformView,
  143. placeholder: KFCrossPlatformImage? = nil,
  144. options: KingfisherOptionsInfo? = nil,
  145. progressBlock: DownloadProgressBlock? = nil,
  146. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  147. {
  148. let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
  149. return setImage(
  150. with: resource.map { .network($0) },
  151. attributedView: attributedView,
  152. placeholder: placeholder,
  153. parsedOptions: options,
  154. progressBlock: progressBlock,
  155. completionHandler: completionHandler
  156. )
  157. }
  158. func setImage(
  159. with source: Source?,
  160. attributedView: @escaping () -> KFCrossPlatformView,
  161. placeholder: KFCrossPlatformImage? = nil,
  162. parsedOptions: KingfisherParsedOptionsInfo,
  163. progressBlock: DownloadProgressBlock? = nil,
  164. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  165. {
  166. var mutatingSelf = self
  167. guard let source = source else {
  168. base.image = placeholder
  169. mutatingSelf.taskIdentifier = nil
  170. completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
  171. return nil
  172. }
  173. var options = parsedOptions
  174. if !options.keepCurrentImageWhileLoading {
  175. base.image = placeholder
  176. }
  177. let issuedIdentifier = Source.Identifier.next()
  178. mutatingSelf.taskIdentifier = issuedIdentifier
  179. if let block = progressBlock {
  180. options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
  181. }
  182. let task = KingfisherManager.shared.retrieveImage(
  183. with: source,
  184. options: options,
  185. progressiveImageSetter: { self.base.image = $0 },
  186. referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier },
  187. completionHandler: { result in
  188. CallbackQueue.mainCurrentOrAsync.execute {
  189. guard issuedIdentifier == self.taskIdentifier else {
  190. let reason: KingfisherError.ImageSettingErrorReason
  191. do {
  192. let value = try result.get()
  193. reason = .notCurrentSourceTask(result: value, error: nil, source: source)
  194. } catch {
  195. reason = .notCurrentSourceTask(result: nil, error: error, source: source)
  196. }
  197. let error = KingfisherError.imageSettingError(reason: reason)
  198. completionHandler?(.failure(error))
  199. return
  200. }
  201. mutatingSelf.imageTask = nil
  202. mutatingSelf.taskIdentifier = nil
  203. switch result {
  204. case .success(let value):
  205. self.base.image = value.image
  206. let view = attributedView()
  207. #if canImport(UIKit)
  208. view.setNeedsDisplay()
  209. #else
  210. view.setNeedsDisplay(view.bounds)
  211. #endif
  212. case .failure:
  213. if let image = options.onFailureImage {
  214. self.base.image = image
  215. }
  216. }
  217. completionHandler?(result)
  218. }
  219. }
  220. )
  221. mutatingSelf.imageTask = task
  222. return task
  223. }
  224. // MARK: Cancelling Image
  225. /// Cancel the image download task bounded to the text attachment if it is running.
  226. /// Nothing will happen if the downloading has already finished.
  227. public func cancelDownloadTask() {
  228. imageTask?.cancel()
  229. }
  230. }
  231. private var taskIdentifierKey: Void?
  232. private var imageTaskKey: Void?
  233. // MARK: Properties
  234. extension KingfisherWrapper where Base: NSTextAttachment {
  235. public private(set) var taskIdentifier: Source.Identifier.Value? {
  236. get {
  237. let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
  238. return box?.value
  239. }
  240. set {
  241. let box = newValue.map { Box($0) }
  242. setRetainedAssociatedObject(base, &taskIdentifierKey, box)
  243. }
  244. }
  245. private var imageTask: DownloadTask? {
  246. get { return getAssociatedObject(base, &imageTaskKey) }
  247. set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
  248. }
  249. }
  250. #endif