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);

}

你可能感兴趣的:(NSURLConnection实现小文件的下载)