IOS文件分段下载

时间:2014-07-22 23:09:35   收藏:0   阅读:435

HTTP HEAD 生成方法

 

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:kTimeout];

request.HTTPMethod = @"HEAD";

[NSURLConnection sendAsynchronousRequest:request queue:self.myQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

    NSLog(@"%@", response);

    NSLog(@"---------------");

    NSLog(@"%@", data);

}];

运行测试代码可以发现,HEAD方法只是返回资源信息,而不会返回数据体

应用场景:

(1)获取资源Mimetype
(2)获取资源文件大小,用于端点续传或多线程下载
 
 
 
使用代码块来获取资源大小的方法

- (void)fileSizeWithURL:(NSURL *)url completion:(void (^)(long long contentLength))completion

{

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:kTimeout];

    request.HTTPMethod = @"HEAD";

    NSURLResponse *response = nil;

    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];

   

    completion(response.expectedContentLength);

}

 
确定每次下载数据包的伪代码实现
 

- (void)downloadFileWithURL:(NSURL *)url

{

    [self fileSizeWithURL:url completion:^(long long contentLength) {

        NSLog(@"文件总大小:%lld", contentLength);       

        // 根据大小下载文件

               while (contentLength > kDownloadBytes) {

            NSLog(@"每次下载长度:%lld", (long long)kDownloadBytes);

            contentLength -= kDownloadBytes;

        }

        NSLog(@"最后下载字节数:%lld", contentLength);

    }];

}

 

分段Range代码实现

long long fromBytes = 0;

long long toBytes = 0;

while (contentLength > kDownloadBytes) {

    toBytes = fromBytes + kDownloadBytes - 1;

    NSString *range = [NSString stringWithFormat:@"bytes=%lld-%lld", fromBytes, toBytes];

    NSLog(@"range %@", range);

    fromBytes += kDownloadBytes;

    contentLength -= kDownloadBytes;

}

fromBytes = fromBytes + contentLength - 1;

NSString *range = [NSString stringWithFormat:@"bytes=%lld-%lld", fromBytes, toBytes];

NSLog(@"range %@", range);

 

分段下载文件

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:kTimeout];

NSString *range = [NSString stringWithFormat:@"bytes=%lld-%lld", from, end];

[request setValue:range forHTTPHeaderField:@"Range"];

 

NSURLResponse *response = nil;

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];

   

NSLog(@"%@-%@-%ld", range, response, (unsigned long)data.length);

 

提示:

如果GET包含Range请求头,响应会以状态码206(PartialContent)返回而不是200(OK)

 

将数据写入文件

 

// 打开缓存文件

NSFileHandle *fp = [NSFileHandle fileHandleForWritingAtPath:self.cachePath];

// 如果文件不存在,直接写入数据

if (!fp) {

    [data writeToFile:self.cachePath atomically:YES];

} else {

    // 移动到文件末尾

    [fp seekToEndOfFile];

    // 将数据文件追加到文件末尾

    [fp writeData:data];

    // 关闭文件句柄

    [fp closeFile];

}

IOS文件分段下载,码迷,mamicode.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!