Resume download functionality in NSURLConnection

2019-03-11 07:17发布

问题:

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?

回答1:

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.



回答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.