大文件斷點下載(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個字節(jié):Range: bytes=0-499
     表示第二個500字節(jié):Range: bytes=500-999
     表示最后500個字節(jié):Range: bytes=-500
     表示500字節(jié)以后的范圍:Range: bytes=500-
     */
    NSString *range = [NSString stringWithFormat:@"bytes=%zd-",self.currentLength];
    
    //規(guī)定下次的下載開始位置
    [request setValue:range forHTTPHeaderField:@"Range"];

    //發(fā)送請求
    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];
    
    //創(chuàng)建文件
    [manager createFileAtPath:fullPath contents:nil attributes:nil];
    
    //每一次都接收新的總數(shù)
    self.totoleLength = response.expectedContentLength + self.currentLength;
    
    //創(chuàng)建文件句柄
    self.handle = [NSFileHandle fileHandleForWritingAtPath:fullPath];

    //從數(shù)據(jù)最后開始寫入數(shù)據(jù)
    [self.handle seekToEndOfFile];

    //輸出流
    /*self.stream = [NSOutputStream outputStreamToFileAtPath:fullPath append:YES];
    
    [self.stream open];*/
    
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //當(dāng)前文件進度
    self.currentLength += data.length;
    
    //寫入文件中
    [self.handle writeData:data];

    /*輸出流寫入數(shù)據(jù)
   [self.stream write:data.bytes maxLength:data.length];
    */
    
    //進度條
    self.progress.progress = 1.0 * self.currentLength / self.totoleLength;
    
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //關(guān)閉文件句柄
    [self.handle closeFile];
    
    self.handle = nil;
    /**
    [self.stream close];
    self.stream = nil;
    */
}
/*
 4.當(dāng)請求失敗的時候調(diào)用該方法
 */
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"Error");
    
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容