소스 검색

Adding documentation to UIButton category

Switching backing of UIButton category to AFURLConnectionOperation
Mattt Thompson 12 년 전
부모
커밋
3bdfefa83b
2개의 변경된 파일144개의 추가작업 그리고 43개의 파일을 삭제
  1. 54 8
      UIKit+AFNetworking/UIButton+AFNetworking.h
  2. 90 35
      UIKit+AFNetworking/UIButton+AFNetworking.m

+ 54 - 8
UIKit+AFNetworking/UIButton+AFNetworking.h

@@ -24,11 +24,12 @@
 
 #import <Availability.h>
 
-#if __IPHONE_OS_VERSION_MIN_REQUIRED
+#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+
 #import <UIKit/UIKit.h>
 
 /**
- 
+ This category adds methods to the UIKit framework's `UIButton` class. The methods in this category provide support for loading remote images and background images asynchronously from a URL.
  */
 @interface UIButton (AFNetworking)
 
@@ -37,20 +38,41 @@
 ///--------------------
 
 /**
+ Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
+ 
+  If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
  
+ @param state The control state.
+ @param url The URL used for the image request.
  */
 - (void)setImageForState:(UIControlState)state
                  withURL:(NSURL *)url;
 
 /**
+ Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
  
+ If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
+ 
+ @param state The control state.
+ @param url The URL used for the image request.
+ @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes.
  */
 - (void)setImageForState:(UIControlState)state
                  withURL:(NSURL *)url
         placeholderImage:(UIImage *)placeholderImage;
 
 /**
+ Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
+
+ If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
  
+ If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setImage:forState:` is applied.
+
+ @param state The control state.
+ @param urlRequest The URL request used for the image request.
+ @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes.
+ @param success A block to be executed when the image request operation finishes successfully. This block has no return value and takes two arguments: the server response and the image. If the image was returned from cache, the request and response parameters will be `nil`.
+ @param failure A block object to be executed when the image request operation finishes unsuccessfully, or that finishes successfully. This block has no return value and takes a single argument: the error that occurred.
  */
 - (void)setImageForState:(UIControlState)state
           withURLRequest:(NSURLRequest *)urlRequest
@@ -64,20 +86,39 @@
 ///-------------------------------
 
 /**
- 
+ Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous background image request for the receiver will be cancelled.
+
+ If the background image is cached locally, the background image is set immediately, otherwise the specified placeholder background image will be set immediately, and then the remote background image will be set once the request is finished.
+
+ @param state The control state.
+ @param url The URL used for the background image request.
  */
 - (void)setBackgroundImageForState:(UIControlState)state
                            withURL:(NSURL *)url;
 
 /**
- 
+ Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
+
+ If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
+
+ @param state The control state.
+ @param url The URL used for the background image request.
+ @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes.
  */
 - (void)setBackgroundImageForState:(UIControlState)state
                            withURL:(NSURL *)url
-                  placeholderImage:(UIImage *)image;
+                  placeholderImage:(UIImage *)placeholderImage;
 
 /**
- 
+ Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
+
+ If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
+
+ If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setBackgroundImage:forState:` is applied.
+
+ @param state The control state.
+ @param urlRequest The URL request used for the image request.
+ @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes.
  */
 - (void)setBackgroundImageForState:(UIControlState)state
                     withURLRequest:(NSURLRequest *)urlRequest
@@ -91,9 +132,14 @@
 ///-------------------------------
 
 /**
- 
+ Cancels any executing image operation for the receiver, if one exists.
+ */
+- (void)cancelImageRequestOperation;
+
+/**
+ Cancels any executing background image operation for the receiver, if one exists.
  */
-- (void)cancelImageDataTasks;
+- (void)cancelBackgroundImageRequestOperation;
 
 @end
 

+ 90 - 35
UIKit+AFNetworking/UIButton+AFNetworking.m

@@ -20,30 +20,57 @@
 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 // THE SOFTWARE.
 
-#import <Foundation/Foundation.h>
+#import "UIButton+AFNetworking.h"
+
 #import <objc/message.h>
 
+#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+
 #import "AFHTTPRequestOperation.h"
-#import "AFHTTPSessionManager.h"
 
-#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
-#import "UIButton+AFNetworking.h"
+static char kAFImageRequestOperationKey;
+static char kAFBackgroundImageRequestOperationKey;
 
-@implementation UIButton (AFNetworking)
+@interface UIButton (_AFNetworking)
+@property (readwrite, nonatomic, strong, setter = af_setImageRequestOperation:) AFHTTPRequestOperation *af_imageRequestOperation;
+@property (readwrite, nonatomic, strong, setter = af_setBackgroundImageRequestOperation:) AFHTTPRequestOperation *af_backgroundImageRequestOperation;
+@end
+
+@implementation UIButton (_AFNetworking)
 
-+ (AFHTTPSessionManager *)af_sharedHTTPClient {
-    static AFHTTPSessionManager *_af_sharedHTTPClient = nil;
++ (NSOperationQueue *)af_sharedImageRequestOperationQueue {
+    static NSOperationQueue *_af_sharedImageRequestOperationQueue = nil;
     static dispatch_once_t onceToken;
     dispatch_once(&onceToken, ^{
-        _af_sharedHTTPClient = [[AFHTTPSessionManager alloc] init];
-        _af_sharedHTTPClient.responseSerializer = [AFImageResponseSerializer serializer];
+        _af_sharedImageRequestOperationQueue = [[NSOperationQueue alloc] init];
+        _af_sharedImageRequestOperationQueue.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount;
     });
 
-    return _af_sharedHTTPClient;
+    return _af_sharedImageRequestOperationQueue;
+}
+
+- (AFHTTPRequestOperation *)af_imageRequestOperation {
+    return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, &kAFImageRequestOperationKey);
+}
+
+- (void)af_setImageRequestOperation:(AFHTTPRequestOperation *)imageRequestOperation {
+    objc_setAssociatedObject(self, &kAFImageRequestOperationKey, imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
 }
 
+- (AFHTTPRequestOperation *)af_backgroundImageRequestOperation {
+    return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, &kAFBackgroundImageRequestOperationKey);
+}
+
+- (void)af_setBackgroundImageRequestOperation:(AFHTTPRequestOperation *)imageRequestOperation {
+    objc_setAssociatedObject(self, &kAFBackgroundImageRequestOperationKey, imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
+@end
+
 #pragma mark -
 
+@implementation UIButton (AFNetworking)
+
 - (void)setImageForState:(UIControlState)state
                  withURL:(NSURL *)url
 {
@@ -66,7 +93,32 @@
                  success:(void (^)(NSHTTPURLResponse *response, UIImage *image))success
                  failure:(void (^)(NSError *error))failure
 {
-    [self setImageWithSelector:@selector(setImage:forState:) forState:state withURLRequest:urlRequest placeholderImage:placeholderImage success:success failure:failure];
+    [self cancelImageRequestOperation];
+
+    [self setImage:placeholderImage forState:state];
+
+    __weak __typeof(self)weakSelf = self;
+    self.af_imageRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
+    [self.af_imageRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
+        __strong __typeof(weakSelf)strongSelf = weakSelf;
+        if ([[urlRequest URL] isEqual:[operation.request URL]]) {
+            if (success) {
+                success(operation.response, responseObject);
+            } else if (responseObject) {
+                [strongSelf setImage:responseObject forState:state];
+            }
+        } else {
+
+        }
+    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
+        if ([[urlRequest URL] isEqual:[operation.response URL]]) {
+            if (failure) {
+                failure(error);
+            }
+        }
+    }];
+
+    [[[self class] af_sharedImageRequestOperationQueue] addOperation:self.af_imageRequestOperation];
 }
 
 #pragma mark -
@@ -93,41 +145,44 @@
                            success:(void (^)(NSHTTPURLResponse *response, UIImage *image))success
                            failure:(void (^)(NSError *error))failure
 {
-    [self setImageWithSelector:@selector(setBackgroundImage:forState:) forState:state withURLRequest:urlRequest placeholderImage:placeholderImage success:success failure:failure];
-}
+    [self cancelBackgroundImageRequestOperation];
 
-#pragma mark -
-
-- (void)setImageWithSelector:(SEL)selector
-                    forState:(UIControlState)state
-              withURLRequest:(NSURLRequest *)urlRequest
-            placeholderImage:(UIImage *)placeholderImage
-                     success:(void (^)(NSHTTPURLResponse *response, UIImage *image))success
-                     failure:(void (^)(NSError *error))failure
-{
+    [self setBackgroundImage:placeholderImage forState:state];
 
-    void (*objc_msgSend_typed)(id, SEL, UIImage *, UIControlState) = (void (*)(id, SEL, UIImage *, UIControlState))objc_msgSend;
-    objc_msgSend_typed(self, selector, placeholderImage, state);
+    __weak __typeof(self)weakSelf = self;
+    self.af_backgroundImageRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
+    [self.af_backgroundImageRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
+        __strong __typeof(weakSelf)strongSelf = weakSelf;
+        if ([[urlRequest URL] isEqual:[operation.request URL]]) {
+            if (success) {
+                success(operation.response, responseObject);
+            } else if (responseObject) {
+                [strongSelf setBackgroundImage:responseObject forState:state];
+            }
+        } else {
 
-    NSURLSessionTask *task = [[[self class] af_sharedHTTPClient] dataTaskWithRequest:urlRequest completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
-        if (error) {
+        }
+    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
+        if ([[urlRequest URL] isEqual:[operation.response URL]]) {
             if (failure) {
                 failure(error);
             }
-        } else {
-            if (success) {
-                success((NSHTTPURLResponse *)response, responseObject);
-            } else if (responseObject) {
-                objc_msgSend_typed(self, selector, responseObject, state);
-            }
         }
     }];
 
-    [task resume];
+    [[[self class] af_sharedImageRequestOperationQueue] addOperation:self.af_backgroundImageRequestOperation];
+}
+
+#pragma mark -
+
+- (void)cancelImageRequestOperation {
+    [self.af_imageRequestOperation cancel];
+    self.af_imageRequestOperation = nil;
 }
 
-- (void)cancelImageDataTasks {
-    [[[[self class] af_sharedHTTPClient] tasks] makeObjectsPerformSelector:@selector(cancel)];
+- (void)cancelBackgroundImageRequestOperation {
+    [self.af_backgroundImageRequestOperation cancel];
+    self.af_backgroundImageRequestOperation = nil;
 }
 
 @end