How do I set a request timeout and cache policy in AFNetworking 2.0?

21,956

Solution 1

I'm a bit lazy to categorize or subclass. You can access the manager's request serializer directly:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer.timeoutInterval = INTERNET_TIMEOUT;
manager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;

Solution 2

The best is to create a subclass

(you can also the same way add cache policy)

TimeoutAFHTTPRequestSerializer.h

#import "AFURLRequestSerialization.h"

@interface TimeoutAFHTTPRequestSerializer : AFHTTPRequestSerializer

@property (nonatomic, assign) NSTimeInterval timeout;

- (id)initWithTimeout:(NSTimeInterval)timeout;

@end

TimeoutAFHTTPRequestSerializer.m

#import "TimeoutAFHTTPRequestSerializer.h"

@implementation TimeoutAFHTTPRequestSerializer

- (id)initWithTimeout:(NSTimeInterval)timeout {

    self = [super init];
    if (self) {
        self.timeout = timeout;
    }
    return self;

}

- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
                                 URLString:(NSString *)URLString
                                parameters:(NSDictionary *)parameters
                                     error:(NSError *__autoreleasing *)error
{
    NSMutableURLRequest *request = [super requestWithMethod:method URLString:URLString parameters:parameters error:error];

    if (self.timeout > 0) {
        [request setTimeoutInterval:self.timeout];
    }
    return request;
}

@end

Use

self.requestOperationManager.requestSerializer = [[TimeoutAFHTTPRequestSerializer alloc] initWithTimeout:30];

Solution 3

You can also create a category AFHTTPRequestOperationManager+timeout to add this method without having to subclass AFHTTPRequestOperationManager.

Solution 4

Try something like :

NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:kRequestTimout];

where kRequestTimout is the timeout duration you want

Then build your serialized request :

NSURLRequest *serializedRequest = [self.requestOperationManager.requestSerializer requestBySerializingRequest:request withParameters:parameters error:&error];

And create & add your request operation :

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:serializedRequest];
[operation setCompletionBlockWithSuccess:successBlock failure:failureBlock];
[self.requestOperationManager.operationQueue addOperation:operation];

Solution 5

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.

Share:
21,956

Related videos on Youtube

joao
Author by

joao

Wherever you go there you are.

Updated on March 18, 2020

Comments

  • joao
    joao over 4 years

    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?

    • rckoenes
      rckoenes over 10 years
      A clean way to the have your own class extend the AFHTTPRequestOperationManager and add the method to that class.
    • joao
      joao over 10 years
      That is indeed a good point... I'll do that for the time being.
    • David Snabel-Caunt
      David Snabel-Caunt over 10 years
      There's no cleaner way. The utility methods are terse and don't include all the parameters that you might want to set.