UIImageView+AFNetworking.m 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. // UIImageView+AFNetworking.m
  2. // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. #import "UIImageView+AFNetworking.h"
  22. #import <objc/runtime.h>
  23. #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
  24. #import "AFHTTPRequestOperation.h"
  25. @interface AFImageCache : NSCache <AFImageCache>
  26. @end
  27. #pragma mark -
  28. @interface UIImageView (_AFNetworking)
  29. @property (readwrite, nonatomic, strong, setter = af_setImageRequestOperation:) AFHTTPRequestOperation *af_imageRequestOperation;
  30. @end
  31. @implementation UIImageView (_AFNetworking)
  32. + (NSOperationQueue *)af_sharedImageRequestOperationQueue {
  33. static NSOperationQueue *_af_sharedImageRequestOperationQueue = nil;
  34. static dispatch_once_t onceToken;
  35. dispatch_once(&onceToken, ^{
  36. _af_sharedImageRequestOperationQueue = [[NSOperationQueue alloc] init];
  37. _af_sharedImageRequestOperationQueue.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount;
  38. });
  39. return _af_sharedImageRequestOperationQueue;
  40. }
  41. - (AFHTTPRequestOperation *)af_imageRequestOperation {
  42. return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, @selector(af_imageRequestOperation));
  43. }
  44. - (void)af_setImageRequestOperation:(AFHTTPRequestOperation *)imageRequestOperation {
  45. objc_setAssociatedObject(self, @selector(af_imageRequestOperation), imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  46. }
  47. @end
  48. #pragma mark -
  49. @implementation UIImageView (AFNetworking)
  50. @dynamic imageResponseSerializer;
  51. + (id <AFImageCache>)sharedImageCache {
  52. static AFImageCache *_af_defaultImageCache = nil;
  53. static dispatch_once_t oncePredicate;
  54. dispatch_once(&oncePredicate, ^{
  55. _af_defaultImageCache = [[AFImageCache alloc] init];
  56. [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidReceiveMemoryWarningNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * __unused notification) {
  57. [_af_defaultImageCache removeAllObjects];
  58. }];
  59. });
  60. #pragma clang diagnostic push
  61. #pragma clang diagnostic ignored "-Wgnu"
  62. return objc_getAssociatedObject(self, @selector(sharedImageCache)) ?: _af_defaultImageCache;
  63. #pragma clang diagnostic pop
  64. }
  65. + (void)setSharedImageCache:(__nullable id <AFImageCache>)imageCache {
  66. objc_setAssociatedObject(self, @selector(sharedImageCache), imageCache, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  67. }
  68. #pragma mark -
  69. - (id <AFURLResponseSerialization>)imageResponseSerializer {
  70. static id <AFURLResponseSerialization> _af_defaultImageResponseSerializer = nil;
  71. static dispatch_once_t onceToken;
  72. dispatch_once(&onceToken, ^{
  73. _af_defaultImageResponseSerializer = [AFImageResponseSerializer serializer];
  74. });
  75. #pragma clang diagnostic push
  76. #pragma clang diagnostic ignored "-Wgnu"
  77. return objc_getAssociatedObject(self, @selector(imageResponseSerializer)) ?: _af_defaultImageResponseSerializer;
  78. #pragma clang diagnostic pop
  79. }
  80. - (void)setImageResponseSerializer:(id <AFURLResponseSerialization>)serializer {
  81. objc_setAssociatedObject(self, @selector(imageResponseSerializer), serializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  82. }
  83. #pragma mark -
  84. - (void)setImageWithURL:(NSURL *)url {
  85. [self setImageWithURL:url placeholderImage:nil];
  86. }
  87. - (void)setImageWithURL:(NSURL *)url
  88. placeholderImage:(UIImage *)placeholderImage
  89. {
  90. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
  91. [request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
  92. [self setImageWithURLRequest:request placeholderImage:placeholderImage success:nil failure:nil];
  93. }
  94. - (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
  95. placeholderImage:(UIImage *)placeholderImage
  96. success:(void (^)(NSURLRequest *request, NSHTTPURLResponse * __nullable response, UIImage *image))success
  97. failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse * __nullable response, NSError *error))failure
  98. {
  99. [self cancelImageRequestOperation];
  100. UIImage *cachedImage = [[[self class] sharedImageCache] cachedImageForRequest:urlRequest];
  101. if (cachedImage) {
  102. if (success) {
  103. success(urlRequest, nil, cachedImage);
  104. } else {
  105. self.image = cachedImage;
  106. }
  107. self.af_imageRequestOperation = nil;
  108. } else {
  109. if (placeholderImage) {
  110. self.image = placeholderImage;
  111. }
  112. __weak __typeof(self)weakSelf = self;
  113. self.af_imageRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
  114. self.af_imageRequestOperation.responseSerializer = self.imageResponseSerializer;
  115. [self.af_imageRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
  116. __strong __typeof(weakSelf)strongSelf = weakSelf;
  117. if ([[urlRequest URL] isEqual:[strongSelf.af_imageRequestOperation.request URL]]) {
  118. if (success) {
  119. success(urlRequest, operation.response, responseObject);
  120. } else if (responseObject) {
  121. strongSelf.image = responseObject;
  122. }
  123. if (operation == strongSelf.af_imageRequestOperation){
  124. strongSelf.af_imageRequestOperation = nil;
  125. }
  126. }
  127. [[[strongSelf class] sharedImageCache] cacheImage:responseObject forRequest:urlRequest];
  128. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  129. __strong __typeof(weakSelf)strongSelf = weakSelf;
  130. if ([[urlRequest URL] isEqual:[strongSelf.af_imageRequestOperation.request URL]]) {
  131. if (failure) {
  132. failure(urlRequest, operation.response, error);
  133. }
  134. if (operation == strongSelf.af_imageRequestOperation){
  135. strongSelf.af_imageRequestOperation = nil;
  136. }
  137. }
  138. }];
  139. [[[self class] af_sharedImageRequestOperationQueue] addOperation:self.af_imageRequestOperation];
  140. }
  141. }
  142. - (void)cancelImageRequestOperation {
  143. [self.af_imageRequestOperation cancel];
  144. self.af_imageRequestOperation = nil;
  145. }
  146. @end
  147. #pragma mark -
  148. static inline NSString * AFImageCacheKeyFromURLRequest(NSURLRequest *request) {
  149. return [[request URL] absoluteString];
  150. }
  151. @implementation AFImageCache
  152. - (UIImage *)cachedImageForRequest:(NSURLRequest *)request {
  153. switch ([request cachePolicy]) {
  154. case NSURLRequestReloadIgnoringCacheData:
  155. case NSURLRequestReloadIgnoringLocalAndRemoteCacheData:
  156. return nil;
  157. default:
  158. break;
  159. }
  160. return [self objectForKey:AFImageCacheKeyFromURLRequest(request)];
  161. }
  162. - (void)cacheImage:(UIImage *)image
  163. forRequest:(NSURLRequest *)request
  164. {
  165. if (image && request) {
  166. [self setObject:image forKey:AFImageCacheKeyFromURLRequest(request)];
  167. }
  168. }
  169. @end
  170. #endif