NSOutputStream-保存网络资源到本地



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];
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值