WKInterfaceImage+Kingfisher.swift 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. //
  2. // WKInterfaceImage+Kingfisher.swift
  3. // Kingfisher
  4. //
  5. // Created by Rodrigo Borges Soares on 04/05/18.
  6. //
  7. // Copyright (c) 2018 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. import WatchKit
  27. extension KingfisherWrapper where Base: WKInterfaceImage {
  28. @discardableResult
  29. public func setImage(
  30. with source: Source?,
  31. placeholder: Image? = nil,
  32. options: KingfisherOptionsInfo? = nil,
  33. progressBlock: DownloadProgressBlock? = nil,
  34. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  35. {
  36. var mutatingSelf = self
  37. guard let source = source else {
  38. base.setImage(placeholder)
  39. mutatingSelf.taskIdentifier = nil
  40. completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
  41. return nil
  42. }
  43. let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
  44. if !options.keepCurrentImageWhileLoading {
  45. base.setImage(placeholder)
  46. }
  47. let issuedTaskIdentifier = issueSourceIdentifier()
  48. mutatingSelf.taskIdentifier = issuedTaskIdentifier
  49. let task = KingfisherManager.shared.retrieveImage(
  50. with: source,
  51. options: options,
  52. progressBlock: { receivedSize, totalSize in
  53. guard issuedTaskIdentifier == self.taskIdentifier else { return }
  54. progressBlock?(receivedSize, totalSize)
  55. },
  56. completionHandler: { result in
  57. CallbackQueue.mainCurrentOrAsync.execute {
  58. guard issuedTaskIdentifier == self.taskIdentifier else {
  59. let error = KingfisherError.imageSettingError(
  60. reason: .notCurrentSourceTask(result: result.value, error: result.error, source: source))
  61. completionHandler?(.failure(error))
  62. return
  63. }
  64. mutatingSelf.imageTask = nil
  65. switch result {
  66. case .success(let value):
  67. self.base.setImage(value.image)
  68. completionHandler?(result)
  69. case .failure:
  70. if let image = options.onFailureImage {
  71. self.base.setImage(image)
  72. }
  73. completionHandler?(result)
  74. }
  75. }
  76. })
  77. mutatingSelf.imageTask = task
  78. return task
  79. }
  80. /// Sets an image to the image view with a requested resource.
  81. ///
  82. /// - Parameters:
  83. /// - resource: The `Resource` object contains information about the resource.
  84. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  85. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  86. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  87. /// `expectedContentLength`, this block will not be called.
  88. /// - completionHandler: Called when the image retrieved and set finished.
  89. /// - Returns: A task represents the image downloading.
  90. ///
  91. /// - Note:
  92. ///
  93. /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
  94. /// or network. Since this method will perform UI changes, you must call it from the main thread.
  95. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
  96. ///
  97. @discardableResult
  98. public func setImage(
  99. with resource: Resource?,
  100. placeholder: Image? = nil,
  101. options: KingfisherOptionsInfo? = nil,
  102. progressBlock: DownloadProgressBlock? = nil,
  103. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  104. {
  105. return setImage(
  106. with: resource.map { .network($0) },
  107. placeholder: placeholder,
  108. options: options,
  109. progressBlock: progressBlock,
  110. completionHandler: completionHandler)
  111. }
  112. /**
  113. Cancel the image download task bounded to the image view if it is running.
  114. Nothing will happen if the downloading has already finished.
  115. */
  116. public func cancelDownloadTask() {
  117. imageTask?.cancel()
  118. }
  119. }
  120. // MARK: - Associated Object
  121. private var taskIdentifierKey: Void?
  122. private var imageTaskKey: Void?
  123. extension KingfisherWrapper where Base: WKInterfaceImage {
  124. public private(set) var taskIdentifier: SourceIdentifier? {
  125. get {
  126. let box: Box<SourceIdentifier>? = getAssociatedObject(base, &taskIdentifierKey)
  127. return box?.value
  128. }
  129. set {
  130. let box = newValue.map { Box($0) }
  131. setRetainedAssociatedObject(base, &taskIdentifierKey, box)
  132. }
  133. }
  134. private var imageTask: DownloadTask? {
  135. get { return getAssociatedObject(base, &imageTaskKey) }
  136. set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
  137. }
  138. }
  139. extension KingfisherWrapper where Base: WKInterfaceImage {
  140. /// Gets the image URL binded to this image view.
  141. @available(*, obsoleted: 5.0, message: "Use `taskIdentifier` instead to identify a setting task.")
  142. public private(set) var webURL: URL? {
  143. get { return nil }
  144. set { }
  145. }
  146. }