大文件下载--NSURLConnection--delegate

    // 1.得到文件的总大小
    self.totalSize = response.expectedContentLength;
    
    // 2.得到沙盒全路径
    self.fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"123.mp4"];
    
    // 3.创建一个空的文件
    [[NSFileManager defaultManager] createFileAtPath:self.fullPath contents:nil attributes:nil];
    // 4.创建文件句柄(指针)
    self.handle = [NSFileHandle fileHandleForWritingAtPath:self.fullPath];

    // 1.移动文件句柄到数据的末尾
    [self.handle seekToEndOfFile];
    
    // 2.写数据到沙盒
    [self.handle writeData:data];
    
    // 3.获取进度
    self.currentSize += data.length;
    
    // 进度=已经下载/文件的总大小
    self.progressView.progress = 1.0 * self.currentSize/self.totalSize;
    // 1.关闭文件句柄
    [self.handle closeFile];
    self.handle = nil;
    
    NSLog(@"%@", self.fullPath);
  • NSURLConnection和Runloop补充
// 设置代理
// 代理方法默认在主线程中调用
NSURLConnection *connect = [NSURLConnection connectionWithRequest:request delegate:self];

// 设置代理方法在哪个线程中调用
// [NSOperation alloc] init] 开子线程
// [NSOperation mainQueue] 不能这样设置
[connect setDelegateQueue:[[NSOperation alloc] init]];
NSURLConnection *connect = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:NO];
[connect setDelegateQueue:[[NSOperation alloc] init]];
// 开始发送请求
[connect start];
  • 发送网络请求的过程放在子线程中操作

dispatch_async(dispatch_get_global_queue(0, 0), ^{
       // 设置代理
       // 代理方法默认在主线程中调用
       // 该方法内部其实会将connect对象作为source添加到当前的runloop中,指定运行模式为默认
       NSURLConnection *connect = [NSURLConnection connectionWithRequest:request delegate:self];
       // 设置代理方法在哪个线程中调用
       [connect setDelegateQueue:[[NSOperation alloc] init]];
    
       [[NSRunloop currentRunloop] run];
});
dispatch_async(dispatch_get_global_queue(0, 0), ^{
       // 设置代理
       // 代理方法默认在主线程中调用
       // 该方法内部其实会将connect对象作为source添加到当前的runloop中,指定运行模式为默认
       NSURLConnection *connect = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:NO];
       // 设置代理方法在哪个线程中调用
       [connect setDelegateQueue:[[NSOperation alloc] init]];
    
       // 开始发送请求
       // 如果connect对象没有添加到runloop中,那么该方法内部会自动的添加到runloop
       // 注意:如果当前的runloop没有开启,那么该方法内部会自动获得当前线程对应的runloop对象,并且开启
       [connect start];
});
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容