I'm following the given example code
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
To change the timeout and cache policy I 'hacked' the library and created
- (AFHTTPRequestOperation *)GET:(NSString *)URLString
parameters:(NSDictionary *)parameters
timeoutInterval:(NSTimeInterval)timeoutInterval
cachePolicy:(NSURLRequestCachePolicy)cachePolicy
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"GET" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters];
[request setTimeoutInterval:timeoutInterval];
[request setCachePolicy:cachePolicy];
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
[self.operationQueue addOperation:operation];
return operation;
}
Is there a clean way of doing this?
The best is to create a subclass
(you can also the same way add cache policy)
TimeoutAFHTTPRequestSerializer.h
TimeoutAFHTTPRequestSerializer.m
Use
Try something like :
where
kRequestTimout
is the timeout duration you wantThen build your serialized request :
And create & add your request operation :
You can also create a category AFHTTPRequestOperationManager+timeout to add this method without having to subclass AFHTTPRequestOperationManager.
I'm a bit lazy to categorize or subclass. You can access the manager's request serializer directly:
Take a look at Method 1 for a cleaner way to do it: https://stackoverflow.com/a/21238330/435040
The difference is that I'm using subclassing and I'm not patching AFNetworking's code.
One thing that I forgot to mention. In that answer I'm only changing the timeout interval, but adding some other caching policy is just 1 more line of code.