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

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


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;


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];


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


matomo