大文件断点下载(NSURLConnection)


/*
*点击下载按钮
*/
- (IBAction)begin:(id)sender
{
    
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_03.mp4"];
    
    //请求对象
    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"];

    //发送请求
    NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
    
    self.conn = conn;
}
/*
*取消下载
*/
- (IBAction)stop:(id)sender
{
    [self.conn cancel];
}
#pragma mark - NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if (self.currentLength > 0) 
    {
        return;
    }

    //文件类
    NSFileManager *manager = [NSFileManager defaultManager];
    
    //沙盒路径
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    //拼接文件
    NSString *fullPath = [caches stringByAppendingPathComponent:response.suggestedFilename];
    
    //创建文件
    [manager createFileAtPath:fullPath contents:nil attributes:nil];
    
    //每一次都接收新的总数
    self.totoleLength = response.expectedContentLength + self.currentLength;
    
    //创建文件句柄
    self.handle = [NSFileHandle fileHandleForWritingAtPath:fullPath];

    //从数据最后开始写入数据
    [self.handle seekToEndOfFile];

    //输出流
    /*self.stream = [NSOutputStream outputStreamToFileAtPath:fullPath append:YES];
    
    [self.stream open];*/
    
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //当前文件进度
    self.currentLength += data.length;
    
    //写入文件中
    [self.handle writeData:data];

    /*输出流写入数据
   [self.stream write:data.bytes maxLength:data.length];
    */
    
    //进度条
    self.progress.progress = 1.0 * self.currentLength / self.totoleLength;
    
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //关闭文件句柄
    [self.handle closeFile];
    
    self.handle = nil;
    /**
    [self.stream close];
    self.stream = nil;
    */
}
/*
 4.当请求失败的时候调用该方法
 */
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"Error");
    
}

你可能感兴趣的:(大文件断点下载(NSURLConnection))