Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resume download functionality in NSURLConnection

I am downloading some very large data from a server with the NSURLConnection class.

How can I implement a pause facility so that I can resume downloading?

like image 705
Biranchi Avatar asked Mar 16 '10 06:03

Biranchi


2 Answers

You can't pause, per-se, but you can cancel a connection, and then create a new one to resume where the old left off. However, the server you're connecting to must support the Range header. Set this to "bytes=size_already_downloaded-", and it should pick up right where you cancelled it.

like image 100
Ben Gottlieb Avatar answered Nov 14 '22 07:11

Ben Gottlieb


To resume downloading and get the rest of the file you can set the Range value in HTTP request header by doing something like this:

- (void)downloadFromUrl:(NSURL*)url toFilePath:(NSString *)filePath {

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url     cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
    if (!request) {
        NSLog(@"Error creating request");
        // Do something
    }
    [request setHTTPMethod:@"GET"];

    // Add header to existing file
    NSFileManager *fm = [NSFileManager defaultManager];
    if([fm fileExistsAtPath:filePath]) {
        NSError *error = nil;      
        NSDictionary * fileProp = [fm attributesOfItemAtPath:filePath error:&error];
        if (error) {
            NSLog(@"Error: %@", [error localizedDescription]);
            // Do something
        } else {
            // Set header to resume 
            long long fileSize = [[fileProp objectForKey:@"NSFileSize"]longLongValue];
            NSString *range = @"bytes=";
            range = [[range stringByAppendingString:[[NSNumber numberWithLongLong:fileSize] stringValue]] stringByAppendingString:@"-"];
            [request setValue:range forHTTPHeaderField:@"Range"];
        }
    }
    NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    if (!connection) {
        NSLog(@"Connection failed.");
        // Do something
    }
}

Also you can use - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response to check if the existing file is fully downloaded by checking the expected size: [response expectedContentLength];. If sizes match you probably want to cancel the connection.

like image 29
user2683922 Avatar answered Nov 14 '22 07:11

user2683922