NSURLConnection大文件下載 NSFileHandle 文件句柄寫入沙盒

#define File [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"box_minion_10.mp4"]

@interface ViewController () <NSURLConnectionDataDelegate>
/** 文件的總長度 */
@property (nonatomic, assign) NSUInteger contentLength;
/** 當前下載的總長度 */
@property (nonatomic, assign) NSUInteger currentLength;
/** 文件句柄對象 */
@property (nonatomic, strong) NSFileHandle *handle;
@end

- (void)downloadVideo{
    NSURL *url = [NSURL URLWithString:@"http://www.example.com:8080/resources/videos/minion_10.mp4"];
    [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url] delegate:self];
}

#pragma mark - <NSURLConnectionDataDelegate>
/**
 * 接收到響應的時候:創(chuàng)建一個空的文件
 */
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response{
    // 獲得文件的總長度
    self.contentLength = [response.allHeaderFields[@"Content-Length"] integerValue];
    // 創(chuàng)建一個空的文件
    [[NSFileManager defaultManager] createFileAtPath:File contents:nil attributes:nil];
    // 創(chuàng)建文件句柄
    self.handle = [NSFileHandle fileHandleForWritingAtPath:File];
}

/**
 * 接收到具體數(shù)據(jù):馬上把數(shù)據(jù)寫入一開始創(chuàng)建好的文件
 */
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    // 指定數(shù)據(jù)的寫入位置 -- 文件內容的最后面
    [self.handle seekToEndOfFile];
    // 寫入數(shù)據(jù)
    [self.handle writeData:data];
    // 拼接總長度
    self.currentLength += data.length;
    // 進度
    CGFloat progress = 1.0 * self.currentLength / self.contentLength;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"%@",File);
    // 2016-08-07 15:18:40.104 大文件下載[53862:817163] /Users/zhaoyingxin/Library/Developer/CoreSimulator/Devices/1146129D-06F4-457B-83AC-B97F3B7ECA32/data/Containers/Data/Application/9BE72A92-EBD5-459F-B0A9-D3317422DD86/Library/Caches/box_minion_10.mp4
    
    // 關閉handle
    [self.handle closeFile];
    self.handle = nil;
    
    // 清空長度
    self.currentLength = 0;
    self.contentLength = 0;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容