大檔案斷點下載(NSURLConnection)

weixin_33716557發表於2016-08-04

/*
*點選下載按鈕
*/
- (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");
    
}

相關文章