开发者

Resume download functionality in NSURLConnection

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

How can I im开发者_如何学Cplement a pause facility so that I can resume downloading?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜