iOS - Increase timeout for AFHTTPRequestOperationManager

Oleg picture Oleg · Jan 20, 2014 · Viewed 11.9k times · Source

I'm downloading JSON data from a very slow server. It takes about a minute to get a resoonse from the server. I use AFNetworking library and my code throws "The request timed out" error:

NSString *urlString = [NSString stringWithFormat:@"%@/account.do?JSON&sysparm_action=getRecords",baseUrlString];

    NSString *login = [[NSUserDefaults standardUserDefaults] objectForKey:@"login"];
    NSString *password = [[NSUserDefaults standardUserDefaults] objectForKey:@"password"];

    [manager setRequestSerializer:[AFHTTPRequestSerializer serializer]];
    [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:login password:password];


    [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
        [self parseJsonWithAccountsData:responseObject];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", operation.responseString);
        [self performSelectorOnMainThread:@selector(failedWithContactsDownload) withObject:nil waitUntilDone:YES];
    }];

Didn't find a way to set a timeout for AFHTTPRequestOperationManager. How can I do it?

Answer

PgmFreek picture PgmFreek · May 14, 2014

In AFNetworking 2 library there is method in AFHTTPRequestSerializer set the request time out interval directly.

NSString *urlString = [NSString stringWithFormat:@"%@/account.do?JSON&sysparm_action=getRecords",baseUrlString];

    NSString *login = [[NSUserDefaults standardUserDefaults] objectForKey:@"login"];
    NSString *password = [[NSUserDefaults standardUserDefaults] objectForKey:@"password"];

    [manager setRequestSerializer:[AFHTTPRequestSerializer serializer]];
    [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:login password:password];
    [manager.requestSerializer setTimeoutInterval:TIME_OUT_INTERVAL];


    [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
        [self parseJsonWithAccountsData:responseObject];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", operation.responseString);
        [self performSelectorOnMainThread:@selector(failedWithContactsDownload) withObject:nil waitUntilDone:YES];
    }];

You don't need to override the class to set the request time out interval.