Skip to content

Instantly share code, notes, and snippets.

@adamkaplan
Last active August 29, 2015 14:14
Show Gist options
  • Save adamkaplan/e304c21e94b8e3b35bec to your computer and use it in GitHub Desktop.
Save adamkaplan/e304c21e94b8e3b35bec to your computer and use it in GitHub Desktop.
Complete Example Code
- (AFHTTPRequestOperation *)GET:(NSString *)urlString
parameters:(NSDictionary *)parameters
success:(void (^)(AFHTTPRequestOperation*,id))success
failure:(void (^)(AFHTTPRequestOperation*,NSError*))failure
{
NSCAssert([NSThread isMainThread], @"must execute on the main thread");
NSURL *url = [[NSURL URLWithString:urlString relativeToURL:self.baseURL] absoluteString];
NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"GET"
URLString:url
parameters:parameters
error:nil];
NSMutableArray *callbacksArray = self.getRequestsDictionary[request.URL];
if (!callbacksArray) {
callbacksArray = [NSMutableArray new];
[self.getRequestsDictionary setObject:callbacksArray forKey:request.URL];
}
[callbacksArray addObject:[[YLSuccessFailureModel alloc]
initWithSuccessBlock:success failureBlock:failure]];
if ([callbacksArray count] > 1) {
return nil;
}
__weak typeof(self) weakSelf = self;
void (^triggerCallbacks)(AFHTTPRequestOperation*, id) =
^void(AFHTTPRequestOperation *operation, id responseOrError) {
NSCAssert([NSThread isMainThread], @"Must be on the main thread");
BOOL failure = [responseOrError isKindOfClass:[NSError class]];
NSURL *url = operation.request.URL;
NSArray *callBacksForRequestBlock = weakSelf.getRequestsDictionary[url]; // ARC retains until end of scope
// Immediately remove the key because some callbacks may actually trigger the same URL,
// and we don't want the de-duper to recognize that fresh call as a duplicate.
[weakSelf.getRequestsDictionary removeObjectForKey:url];
for (YLSuccessFailureModel *successFailureObject in callBacksForRequestBlock) {
if (failure) {
if (successFailureObject.failure) {
successFailureObject.failure(operation, responseOrError);
}
} else if (successFailureObject.success) {
successFailureObject.success(operation, responseOrError);
}
}
};
return [super GET:URLString parameters:parameters
success:triggerCallbacks
failure:triggerCallbacks];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment