解决下载文件过程中内存暴涨之---OutputStream

一、 OutputStream

功能:使用OutputStream来解决下载文件过程中内存暴涨的问题!

我们怎么理解OutputStream就像是水流一样,我们通过水流将数据像流一样保存到某个水塔中,内存中的流会一直连续的流动到水塔中。所以我们需要做的操作是在接到响应的时候,打开水流,在接收数据的时候,就像是水流一直流向水塔!直到水都流完了,我们需要关闭水流!

NSStream 流 抽象类

  • (void)open;

  • (void)close;

NSOutputStream 输出流

在内存和硬盘之间创建一个管道,运送一些字节

把字节通过流写入文件

  • (NSInteger)write:(const uint8_t *)buffer maxLength:(NSUInteger)len;

下载完响应头

//初始化流

NSString *path = @"/Users/xxxxx/Desktop/4444.mp4";

self.stream = [NSOutputStream outputStreamToFileAtPath:path append:YES];

//打开流 如果文件不存在会自动创建文件

[self.stream open];

下载结束或下载出错,关闭流

下载的过程中,写入文件

[self.stream write:data.bytes maxLength:data.length];

问题:

如果文件已经存在,再次下载的时候会追加文件

在文件下载之前,先判断时候有文件,如果则删除重新下载

删除文件,如果文件不存在,此代码什么都不会执行

[[NSFileManager defaultManager] removeItemAtPath:path error:NULL];

步骤:

1>创建并打开流

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    
    self.stream = [NSOutputStream outputStreamToFileAtPath:@"/Users/Apple/Desktop/2222.hm" append:YES];
    
    [self.stream open];
    
}

2>一点点的接收数据的同时将数据写入本地

-   (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    
    [self.stream write:data.bytes maxLength:data.length];
    
}

3>下载完成的方法里面关闭流

-   (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    
    [self.stream close];
    
}

posted on 2016-03-06 16:28  cule  阅读(784)  评论(0)    收藏  举报

导航