AFNetworking2: Cancel Requests With Path

AFNetworking2: Cancel Requests With Path

I ran into a pretty stupid gotcha tonight. I have to admit I blamed AFNetworking straight away. I saw that AFHttpRequestOperationManager wasn’t a singleton, and fair enough, that’s up to you to decide how many managers you want. So here’s how I got to cancelling my urls, subclassing!

//
//  JTHTTPRequestOperationManager.h
//  Created by Richard S on 19/03/2014.
//  Copyright (c) 2014 Jotlab. All rights reserved.
//

#import "AFHTTPRequestOperationManager.h"

@interface JTHTTPRequestOperationManager : AFHTTPRequestOperationManager

+ (instancetype)manager;
- (void)cancelAllHTTPOperationsWithPath:(NSString *)path;

@end
//
//  JTHTTPRequestOperationManager.m
//  Created by Richard S on 19/03/2014.
//  Copyright (c) 2014 Jotlab. All rights reserved.
//

#import "JTHTTPRequestOperationManager.h"

@implementation JTHTTPRequestOperationManager

+ (instancetype)manager {
	static id sharedInstance = nil;
	
	static dispatch_once_t onceToken;
	dispatch_once(&onceToken, ^{
		sharedInstance = [[self alloc] init];
	});
	
	return sharedInstance;
}

- (void)cancelAllHTTPOperationsWithPath:(NSString *)path {
	NSArray *operations = [JTHTTPRequestOperationManager manager].operationQueue.operations;
	for (AFHTTPRequestOperation *operation in operations) {
		NSString *url = [[operation.request.URL baseURL] absoluteString];
		NSRange range = [url rangeOfString:path];
		if (range.location != NSNotFound) {
			NSLog(@"Cancelled request");
			[operation cancel];
		}
	}
}

@end

Posted by voidet

Categorised under ios
Bookmark the permalink or leave a trackback.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

or