大文件下载+Progress+暂停

2016-06-28  本文已影响53人  952625a28d0d
#import "ViewController.h"

@interface ViewController ()<NSURLConnectionDataDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *imagView;
@property (weak, nonatomic) IBOutlet UIProgressView *progress;  // 进度条

- (IBAction)startBtnClick:(id)sender;   // 开始下载
- (IBAction)suspendBtnClick:(id)sender; // 暂停下载

//当前已经下载文件的大小
@property (nonatomic, assign) NSInteger currentLength;
//下载文件的总大小
@property (nonatomic, assign) NSInteger totalLength;
@property (nonatomic, strong)  NSString *fullPath;
//文件句柄
@property (nonatomic, strong) NSFileHandle *handle ;

@property (nonatomic, strong) NSURLConnection *connect;
@end

@implementation ViewController

//开始下载
- (IBAction)startBtnClick:(id)sender {
    
    //1.确定请求路径
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"];
    //2.创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    /*
     表示头500个字节:Range: bytes=0-499
     表示第二个500字节:Range: bytes=500-999
     表示最后500个字节:Range: bytes=-500
     表示500字节以后的范围:Range: bytes=500-
     */
    NSString *range = [NSString stringWithFormat:@"bytes=%zd-",self.currentLength];
    [request setValue:range forHTTPHeaderField:@"Range"];
    NSLog(@"%@",range);
    
    //3.设置代理,发送请求
    NSURLConnection *connect =  [NSURLConnection connectionWithRequest:request delegate:self];
    self.connect = connect;
}
//暂停
- (IBAction)suspendBtnClick:(id)sender {
    
    NSLog(@"暂停--------------------%zd-",self.currentLength);
    
    [self.connect cancel];
}

#pragma mark  NSURLConnectionDataDelegate  start

/*
 1.接收到服务器响应的适合调用
 */
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"+++++++++++");
    
    // 说明是暂停下载
    if (self.currentLength > 0) {
        return;
    }
    
    // 初始化文件管理器
    NSFileManager *manager = [NSFileManager defaultManager];
    
    // 保存下载的文件到沙盒
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    //拼接文件全路径(这里采用的是文件响应系统建议的文件名字)
    NSString *fullPath = [caches stringByAppendingPathComponent:response.suggestedFilename];
    
    // 赋值给全路径
    self.fullPath = fullPath;
    
    //创建文件
    [manager createFileAtPath:fullPath contents:nil attributes:nil];
    
    NSLog(@"%@",fullPath);
    
    //拿到文件的总大小
    self.totalLength = response.expectedContentLength + self.currentLength;
    
    NSLog(@"%zd",self.totalLength);
    
    //创建文件句柄,指向数据写入的文件
    self.handle = [NSFileHandle fileHandleForWritingAtPath:self.fullPath];
    
    //指向从文件的末尾
    [self.handle seekToEndOfFile];
}

/*
 2.接收到服务器返回的数据,会调用多次
 */
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    
    // 保存当前下载文件的进度
    self.currentLength +=data.length;
    
    // 写数据
    [self.handle writeData:data];
    
    // 设置Progress进度条的长度
    NSLog(@"%f",1.0 *self.currentLength / self.totalLength);
    self.progress.progress = 1.0 *self.currentLength / self.totalLength;
}

/*
 3.当请求完成之后调用该方法
 */
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"connectionDidFinishLoading");
    
    // 结束 滞空文件句柄
    [self.handle closeFile];
    self.handle = nil;
}

/*
 4.当请求失败的适合调用该方法,如果失败那么error有值
 */
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError");
    
}

@end```


![DownloadData.gif](https://img.haomeiwen.com/i189984/32cf50c7d652bb8a.gif?imageMogr2/auto-orient/strip)

![DownloadDataaa.gif](https://img.haomeiwen.com/i189984/2dbec68ebd43c649.gif?imageMogr2/auto-orient/strip)
上一篇下一篇

猜你喜欢

热点阅读