Request+AlamofireImage.swift 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. // Request+AlamofireImage.swift
  2. //
  3. // Copyright (c) 2015-2016 Alamofire Software Foundation (http://alamofire.org/)
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. import Alamofire
  23. import Foundation
  24. #if os(iOS) || os(tvOS)
  25. import UIKit
  26. #elseif os(watchOS)
  27. import UIKit
  28. import WatchKit
  29. #elseif os(OSX)
  30. import Cocoa
  31. #endif
  32. extension Request {
  33. static var acceptableImageContentTypes: Set<String> = [
  34. "image/tiff",
  35. "image/jpeg",
  36. "image/gif",
  37. "image/png",
  38. "image/ico",
  39. "image/x-icon",
  40. "image/bmp",
  41. "image/x-bmp",
  42. "image/x-xbitmap",
  43. "image/x-win-bitmap"
  44. ]
  45. /**
  46. Adds the content types specified to the list of acceptable images content types for validation.
  47. - parameter contentTypes: The additional content types.
  48. */
  49. public class func addAcceptableImageContentTypes(contentTypes: Set<String>) {
  50. Request.acceptableImageContentTypes.unionInPlace(contentTypes)
  51. }
  52. // MARK: - iOS, tvOS and watchOS
  53. #if os(iOS) || os(tvOS) || os(watchOS)
  54. /**
  55. Creates a response serializer that returns an image initialized from the response data using the specified
  56. image options.
  57. - parameter imageScale: The scale factor used when interpreting the image data to construct
  58. `responseImage`. Specifying a scale factor of 1.0 results in an image whose
  59. size matches the pixel-based dimensions of the image. Applying a different
  60. scale factor changes the size of the image as reported by the size property.
  61. `Screen.scale` by default.
  62. - parameter inflateResponseImage: Whether to automatically inflate response image data for compressed formats
  63. (such as PNG or JPEG). Enabling this can significantly improve drawing
  64. performance as it allows a bitmap representation to be constructed in the
  65. background rather than on the main thread. `true` by default.
  66. - returns: An image response serializer.
  67. */
  68. public class func imageResponseSerializer(
  69. imageScale imageScale: CGFloat = Request.imageScale,
  70. inflateResponseImage: Bool = true)
  71. -> ResponseSerializer<UIImage, NSError>
  72. {
  73. return ResponseSerializer { request, response, data, error in
  74. guard error == nil else { return .Failure(error!) }
  75. guard let validData = data where validData.length > 0 else {
  76. return .Failure(Request.imageDataError())
  77. }
  78. guard Request.validateContentTypeForRequest(request, response: response) else {
  79. return .Failure(Request.contentTypeValidationError())
  80. }
  81. do {
  82. let image = try Request.imageFromResponseData(validData, imageScale: imageScale)
  83. if inflateResponseImage { image.af_inflate() }
  84. return .Success(image)
  85. } catch {
  86. return .Failure(error as NSError)
  87. }
  88. }
  89. }
  90. /**
  91. Adds a handler to be called once the request has finished.
  92. - parameter imageScale: The scale factor used when interpreting the image data to construct
  93. `responseImage`. Specifying a scale factor of 1.0 results in an image whose
  94. size matches the pixel-based dimensions of the image. Applying a different
  95. scale factor changes the size of the image as reported by the size property.
  96. This is set to the value of scale of the main screen by default, which
  97. automatically scales images for retina displays, for instance.
  98. `Screen.scale` by default.
  99. - parameter inflateResponseImage: Whether to automatically inflate response image data for compressed formats
  100. (such as PNG or JPEG). Enabling this can significantly improve drawing
  101. performance as it allows a bitmap representation to be constructed in the
  102. background rather than on the main thread. `true` by default.
  103. - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 4
  104. arguments: the URL request, the URL response, if one was received, the image,
  105. if one could be created from the URL response and data, and any error produced
  106. while creating the image.
  107. - returns: The request.
  108. */
  109. public func responseImage(
  110. imageScale: CGFloat = Request.imageScale,
  111. inflateResponseImage: Bool = true,
  112. completionHandler: Response<Image, NSError> -> Void)
  113. -> Self
  114. {
  115. return response(
  116. responseSerializer: Request.imageResponseSerializer(
  117. imageScale: imageScale,
  118. inflateResponseImage: inflateResponseImage
  119. ),
  120. completionHandler: completionHandler
  121. )
  122. }
  123. private class func imageFromResponseData(data: NSData, imageScale: CGFloat) throws -> UIImage {
  124. if let image = UIImage.af_threadSafeImageWithData(data, scale: imageScale) {
  125. return image
  126. }
  127. throw imageDataError()
  128. }
  129. private class var imageScale: CGFloat {
  130. #if os(iOS) || os(tvOS)
  131. return UIScreen.mainScreen().scale
  132. #elseif os(watchOS)
  133. return WKInterfaceDevice.currentDevice().screenScale
  134. #endif
  135. }
  136. #elseif os(OSX)
  137. // MARK: - OSX
  138. /**
  139. Creates a response serializer that returns an image initialized from the response data.
  140. - returns: An image response serializer.
  141. */
  142. public class func imageResponseSerializer() -> ResponseSerializer<NSImage, NSError> {
  143. return ResponseSerializer { request, response, data, error in
  144. guard error == nil else { return .Failure(error!) }
  145. guard let validData = data where validData.length > 0 else {
  146. return .Failure(Request.imageDataError())
  147. }
  148. guard Request.validateContentTypeForRequest(request, response: response) else {
  149. return .Failure(Request.contentTypeValidationError())
  150. }
  151. guard let bitmapImage = NSBitmapImageRep(data: validData) else {
  152. return .Failure(Request.imageDataError())
  153. }
  154. let image = NSImage(size: NSSize(width: bitmapImage.pixelsWide, height: bitmapImage.pixelsHigh))
  155. image.addRepresentation(bitmapImage)
  156. return .Success(image)
  157. }
  158. }
  159. /**
  160. Adds a handler to be called once the request has finished.
  161. - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 4
  162. arguments: the URL request, the URL response, if one was received, the image, if
  163. one could be created from the URL response and data, and any error produced while
  164. creating the image.
  165. - returns: The request.
  166. */
  167. public func responseImage(completionHandler: Response<Image, NSError> -> Void) -> Self {
  168. return response(
  169. responseSerializer: Request.imageResponseSerializer(),
  170. completionHandler: completionHandler
  171. )
  172. }
  173. #endif
  174. // MARK: - Private - Shared Helper Methods
  175. private class func validateContentTypeForRequest(
  176. request: NSURLRequest?,
  177. response: NSHTTPURLResponse?)
  178. -> Bool
  179. {
  180. if let URL = request?.URL where URL.fileURL {
  181. return true
  182. }
  183. if let mimeType = response?.MIMEType where Request.acceptableImageContentTypes.contains(mimeType) {
  184. return true
  185. }
  186. return false
  187. }
  188. private class func contentTypeValidationError() -> NSError {
  189. let failureReason = "Failed to validate response due to unacceptable content type"
  190. return Error.errorWithCode(NSURLErrorCannotDecodeContentData, failureReason: failureReason)
  191. }
  192. private class func imageDataError() -> NSError {
  193. let failureReason = "Failed to create a valid Image from the response data"
  194. return Error.errorWithCode(NSURLErrorCannotDecodeContentData, failureReason: failureReason)
  195. }
  196. }