iOS之网络下载文件
作者:互联网
文件下载
文件下载在我们日常开发中经常使用到,比如:图片,音频,视频等
简单的小文件下载
- get异步下载
- (void)viewDidLoad {
[super viewDidLoad];
NSString *urlStr = @"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1560231628392&di=1ea41537c16f8045d212ef09b24746cc&imgtype=0&src=http%3A%2F%2Fg.hiphotos.baidu.com%2Fzhidao%2Fpic%2Fitem%2F7acb0a46f21fbe094542faa760600c338744ad60.jpg";
NSURL *url = [NSURL URLWithString:urlStr];
//创建请求
NSURLRequest *requst = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
//创建一个线程
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:requst queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//data是下载的数据
UIImage *image = [UIImage imageWithData:data];
//回到主线程
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.imageView.image = image;
}];
}];
}
- 代理方法 监听就现在
用本地服务器下载一个短视频本地服务器的搭建
可以点击这里查看
//懒加载 属性
- (NSMutableData *)finData {
if (!_finData) {
_finData = [NSMutableData data];
}
return _finData;
}
- (void)viewDidLoad {
[super viewDidLoad];
NSString *urlStr = @"http://localhost/video.mp4";
NSURL *url = [NSURL URLWithString:urlStr];
//创建请求
NSURLRequest *requst = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
//设置代理 遵循协议
[[NSURLConnection alloc] initWithRequest:requst delegate:self];
}
//收到响应
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
//获取到 总数据的大小
self.totalLength = response.expectedContentLength;
}
//接受数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
//拼接数据
[self.finData appendData:data];
//计算下载
NSLog(@"%f", 1.0 *self.finData.length/self.totalLength);
}
//失败的时候
- (void)connection:(NSURLConnection *)connection didFailWithError:(nonnull NSError *)error{
}
//加载完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
// NSLog(@"完成---%@",self.finData);
self.finData = nil;
}
大文件下载
NSFileManager
点击这里查看NSFileHandle
文件句柄 指针 ,注意
:在不用这个对象实例的时候,一定要关闭
当大文件在 下载的时候,我们需要用到
NSFileHandle
指针类指向,接受文件的数据拼接成一个完成的数据
,当然我们也需要NSFileManager
创建一个空文件
来存储接受的数据
- (void)viewDidLoad {
[super viewDidLoad];
NSString *urlStr = @"http://localhost/video.mp4";
NSURL *url = [NSURL URLWithString:urlStr];
//创建请求
NSURLRequest *requst = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
[[NSURLConnection alloc] initWithRequest:requst delegate:self];
}
//收到响应
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
self.totalLength = response.expectedContentLength;
//获取文件路径
NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
self.fullpath = [cachePath stringByAppendingPathComponent:@"123.mp4"];
//创建一个空文件
[[NSFileManager defaultManager] createFileAtPath:self.fullpath contents:nil attributes:nil];
//创建文件指针
self.handle = [NSFileHandle fileHandleForWritingAtPath:self.fullpath];
}
//接受数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
self.currentLegth += data.length;
//接受到数据时 将指针 移动数据的末尾
[self.handle seekToEndOfFile];
//写入文件
[self.handle writeData:data];
NSLog(@"%f",1.0 * self.currentLegth/self.totalLength);
}
//失败的时候
- (void)connection:(NSURLConnection *)connection didFailWithError:(nonnull NSError *)error{
}
//加载完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
//下载完成关闭 指针
[self.handle closeFile];
self.handle = nil;
}
断点下载
- 主要是设置
请求头
的内容 - 原理:根据当前下载文件的大小(记录),设置到
请求头
再次下载的时候,从当前记录的位置开始下载
///开始下载
- (IBAction)handleStartAction:(UIButton *)sender {
NSString *urlStr = @"http://localhost/video.mp4";
NSURL *url = [NSURL URLWithString:urlStr];
//创建请求
NSMutableURLRequest *requst = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
//设置请求头
//从当前在下在文件的大小 开始下载 self.currentLegth 记录之前下载的位置
NSString *rangeByte = [NSString stringWithFormat:@"bytes=%zd-",self.currentLegth];
[requst setValue:rangeByte forHTTPHeaderField:@"Range"];
self.connection = [[NSURLConnection alloc] initWithRequest:requst delegate:self];
}
///取消i下载
- (IBAction)handleCancleAction:(UIButton *)sender {
[self.connection cancel];
}
//收到响应
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
//再次下载的时候,如果已经存在了,就直接return,从记录的位置下载
if (self.currentLegth > 0) {
return;
}
self.totalLength = response.expectedContentLength;
//获取文件路径
NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
self.fullpath = [cachePath stringByAppendingPathComponent:@"123.mp4"];
//创建一个空文件
[[NSFileManager defaultManager] createFileAtPath:self.fullpath contents:nil attributes:nil];
//创建文件指针
self.handle = [NSFileHandle fileHandleForWritingAtPath:self.fullpath];
}
//接受数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
self.currentLegth += data.length;
//接受到数据时 将指针 移动数据的末尾
[self.handle seekToEndOfFile];
//写入文件
[self.handle writeData:data];
self.proviessView.progress = 1.0 * self.currentLegth/self.totalLength;
NSLog(@"%f",1.0 * self.currentLegth/self.totalLength);
}
//失败的时候
- (void)connection:(NSURLConnection *)connection didFailWithError:(nonnull NSError *)error{
}
//加载完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
//下载完成关闭 指针
[self.handle closeFile];
self.handle = nil;
}
标签:self,iOS,网络,connection,NSURLConnection,data,void,下载 来源: https://blog.csdn.net/chase20150628/article/details/91416988