Resume download functionality in NSURLConnection

情到浓时终转凉″ 提交于 2019-12-02 21:04:40

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!