1.确定URL路径
NSURL *url = [NSURL URLWithString:@""];
2.根据URL创建请求对象
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
3.发送请求(代理方法实现下载文件)
[[NSURLConnection alooc] initWithRequest:request delegate:self];
4.实现代理方法(直接将文件写在沙盒里)
/** 沙盒地址 */
@property(nonatomic,strong) NSString fullPath;
/ 数据总大小 /
@property(nonatomic,assign) NSInteger totalSize;
/ 当前数据大小 /
@property(nonatomic,assign) NSInteger currentSize;
/ 输出流 **/
@property(nonatomic,strong) NSOutputStream *stream;
- 当接收到服务器响应时调用,response为响应头部
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
//1.获得文件总大小(本次请求的文件数据的总大小)
self.totalSize = response.expectedContentLength;
//2.写数据到沙盒
self.fullPath = [[NSSearchPathForDirectoriesInDomains(NSCacheDirector , NSUserDomainMask , YES) lastObject] stringByAppendingPathComponent:@"123.mp4"];
//3.创建输出流
/*
第一个参数:文件的路径
第二个参数:YES追加
特点:如果该输出流指向的地址没有文件,那么会自动创建一个空的文件
*/
self.stream = [[NSOutputStream alloc] initToFileAtPath:self.fullPath append:YES];
//4.打开输出流
[stream open];
}
- 接收到服务返回的数据时调用,多次调用,直至接受到全部数据,每次接受一部分数据,放入到data中
- (void)connection:(NSURLConnection *)connection didReceiveData:(nonnull NSData *)data{
//写数据
[self.stream write:data.bytes maxLength:data.length];
//获得进度
self.currentSize += data.length;
//进度
NSLog(@"%f" , 1.0 * self.currentSize / self.totalSize);
}
数据接收完成是调用
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
//1.关闭流
[self.stream close];
self.stream = nil;
}