iOS --下载文件的方法,大文件下载FileHandle

1.小文件的下载方法

        A.NSURL *url = [NSURLURLWithString:@"http://image2.sina.com.cn/ent/v/m/p/2005-11-11/U92P28T3D893697F329DT20051111200426.jpg"];

        NSData *data = [NSDatadataWithContentsOfURL:url];

        NSLog(@"%@",data);

        

        B.[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:url] queue:[NSOperationQueuemainQueue] completionHandler:^(NSURLResponse *_Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {

                NSLog(@"%@",data);

        }];

        

        C.[NSURLConnectionconnectionWithRequest:[NSURLRequestrequestWithURL:url] delegate:self];


2.获取文件大小的方法:两种方法:(nonnull NSURLResponse *)response -》response.expectedContentLength;

(NSHTTPURLResponse *)response -》[response.allHeaderFields[@"Content-Length"]floatValue];

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response{

//(nonnull NSURLResponse *)response{

//        _totalData = response.expectedContentLength;

        _totalData = [response.allHeaderFields[@"Content-Length"]floatValue];

        NSLog(@"%s,%lld",__func__,response.expectedContentLength);

}


3.NSURLConnection 需要手动写入沙盒

        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES)lastObject];

        NSString *file = [cachesstringByAppendingPathComponent:@"hahah.jpg"];

        [self.responseDatawriteToFile:file atomically:YES];

        self.responseData =nil;


4.大文件分段下载: NSFileHandle

#define WXYFile [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"hahah.jpg"]


      //创建文件句柄对象

        NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:WXYFile];

        

  //指定分段下载数据的写入位置

        [handle seekToEndOfFile];

        [handle writeData:data];

        

      //关闭handle,下载完成后

[handle closeFile];

self.handle = nil;


self.contentLenght = [response.allHeaderField[@"Content-Length"]floatValue];

self.currentLenght += data.length;

self.progressView.progress = 1.0 * self.currentLenght / self.contentLength;



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值