NSURLConnection实现小文件的下载

1.简单的实现小文件的下载

NSURL *url = [NSURL URLWithString:@"文件下载地址"];

//2.创建请求对象

NSURLRequest *request = [NSURLRequest requestWithURL:url];

//3.发送请求

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {

//4.写数据到沙盒中

NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:@"123.mp4"];

[data writeToFile:fullPath atomically:YES];

}];

在iOS9.0以后使用NSURLSession类,之前用NSURLConnection来实现网络的请求,该种方法虽然可以下载小文件但是存在问题:

1.无法监听下载精度;

2.内存会随着文件的大小飙升

2.简单的实现小文件的下载(实现监听下载进度设置代理)

NSURL *url = [NSURL URLWithString:@"文件下载地址"];

//2.创建请求对象

NSURLRequest *request = [NSURLRequest requestWithURL:url];

//3.发送请求

[[NSURLConnection alloc]initWithRequest:request delegate:self];

通过代理方法实现下载进度的监听

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

//得到文件的总大小(本次请求的文件数据的总大小)

self.totalSize = response.expectedContentLength;

}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

[self.fileData appendData:data];

//进度=已经下载/文件的总大小

NSLog(@"%f",1.0 * self.fileData.length /self.totalSize);

}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection

{

//4.写数据到沙盒中

NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:@"123.mp4"];

[self.fileData writeToFile:fullPath atomically:YES];

NSLog(@"%@",fullPath);

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容