NSOutputStream
- 流,数据传输的管道,一点儿一点儿下载,一点儿一点儿传输.
NSOutputStream使用步骤 :
1.获取文件保存的路径.
2.客户端跟服务器建立好链接,得到响应体之后就创建好管道,并打开管道.
3.每次接收一点数据就传输一点数据.
4.文件下载完成,关闭管道.
NSOutputStream实现文件缓存
--demo---
#import "FileDownloader.h"
@interfaceFileDownloader ()<NSURLConnectionDataDelegate>
//文件总大小
@property (nonatomic,assign) longlong expectedLength;
//已下载的文件总大小
@property (nonatomic,assign) longlong currentTotalLength;
//内存缓存数据
@property (nonatomic,strong) NSMutableData *dataM;
//流
@property (nonatomic,strong) NSOutputStream *stream;
@end
- 获取响应头 : 创建管道并打开
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"response %@",response);
// 文件总大小
self.expectedLength = response.expectedContentLength;
NSLog(@"文件总大小 : %lld",self.expectedLength);
// 文件保存的路径
NSString *filePath = @"/Users/zhangjie/Desktop/sogou.zip";
// 创建管道
self.stream = [NSOutputStream outputStreamToFileAtPath:filePath append:YES];
// 打开管道
[self.stream open];
}
- 一点儿一点儿接收文件数据,一点儿一点儿传输文件数据到沙盒
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// data : 本次接收的数据,拼接这个数据可以得到已经接收的文件的总大小
self.currentLength += data.length;
// 计算下载进度
float process = (float)self.currentLength / self.expectedLength;
NSLog(@"进度 : %f",process);
// 传输数据 : 内存-->沙盒,下载一点儿就传输一点儿
[self.stream write:data.bytes maxLength:data.length];
}
- 文件下载完成关闭管道
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"文件下载完成");
// 文件下载完成就关闭管道
[self.stream close];
}