今天須要用AFNetworking實現斷點續傳的功能,可是在進行了一番研究以後,發現AFNetworking雖然支持下載文件的暫停和繼續,可是程序從新啓動後再次下載沒法進行續傳。網上有說能夠經過AFDownloadRequestOperation這個AFNetworking的擴展庫來實現從新啓動後的續傳,可是通過本人測試,這個庫在最新的AFNetworking上會報錯,無奈之下,參考他的代碼,本身實現了一個,在這裏分享給你們。xcode
實現的代碼以下:緩存
- - (unsigned long long)fileSizeForPath:(NSString *)path {
- signed long long fileSize = 0;
- NSFileManager *fileManager = [NSFileManager new];
- if ([fileManager fileExistsAtPath:path]) {
- NSError *error = nil;
- NSDictionary *fileDict = [fileManager attributesOfItemAtPath:path error:&error];
- if (!error && fileDict) {
- fileSize = [fileDict fileSize];
- }
- }
- return fileSize;
- }
- - (void)startDownload {
- NSString *downloadUrl = @"http://www.xxx.com/xxx.zip";
- NSString *cacheDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
- NSString *downloadPath = [cacheDirectory stringByAppendingPathComponent:@"xxx.zip"];
- NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:downloadUrl]];
-
- unsigned long long downloadedBytes = 0;
- if ([[NSFileManager defaultManager] fileExistsAtPath:downloadPath]) {
-
- downloadedBytes = [self fileSizeForPath:downloadPath];
- if (downloadedBytes > 0) {
- NSMutableURLRequest *mutableURLRequest = [request mutableCopy];
- NSString *requestRange = [NSString stringWithFormat:@"bytes=%llu-", downloadedBytes];
- [mutableURLRequest setValue:requestRange forHTTPHeaderField:@"Range"];
- request = mutableURLRequest;
- }
- }
-
- [[NSURLCache sharedURLCache] removeCachedResponseForRequest:request];
-
- AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
-
- operation.outputStream = [NSOutputStream outputStreamToFileAtPath:downloadPath append:YES];
-
- [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
-
- float progress = ((float)totalBytesRead + downloadedBytes) / (totalBytesExpectedToRead + downloadedBytes);
- }];
-
- [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
-
- } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
-
- }];
- [operation start];
- }
須要注意的是,此種寫法僅適用於下載zip包,由於下載其餘格式的文件有可能出現數據過多的狀況。當文件已經下載完成時,再次調用該函數,沒法判斷文件是否已經下載完整,因而會再次下載,此時服務器會報416錯,同時返回也會輸出到文件中,使得文件大小異常。可是zip格式不受影響。服務器
感謝分享app