Resume download functionality in NSURLConnection
Asked Answered
A

2

11

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?

Aqaba answered 16/3, 2010 at 6:37 Comment(1)
have you succeeded implementing the pause facility?Fulminous
D
15

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.

Demure answered 16/3, 2010 at 12:30 Comment(0)
P
2

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.

Philpott answered 18/9, 2013 at 21:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.