AFNetworking 实现下载功能(总结)

来源:互联网 发布:mysql的端口号 编辑:程序博客网 时间:2024/06/01 07:55
 NSError * error = nil;    // 创建下载队列    NSOperationQueue * downloadOperationQueue = [[NSOperationQueue alloc]init];    //  规定operationQueue中,最大可以同时执行的operation数量为1    downloadOperationQueue.maxConcurrentOperationCount = 1;    // 创建单个下载任务(访问已下载部分的文件,实现断点续传)

NSMutableURLRequest * downloadRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:DOWNLOAD_URL_STRING]];    [[NSURLCache sharedURLCache]removeCachedResponseForRequest:downloadRequest];//创建请求<pre name="code" class="objc"> AFHTTPRequestOperation * downloadOperation = [[AFHTTPRequestOperation alloc]initWithRequest:downloadRequest];    unsigned long long downloadedPartFileSize = 0;    if ([[NSFileManager defaultManager] fileExistsAtPath:DOWNLOADED_PART_FILE_PATH]) {        NSDictionary * fileAttributes = [[NSFileManager defaultManager]attributesOfItemAtPath:DOWNLOADED_PART_FILE_PATH error:&error];        downloadedPartFileSize = [fileAttributes fileSize];        NSString * headerRangeFieldValue = [NSString stringWithFormat:@"bytes=%llu-", downloadedPartFileSize];        [downloadRequest setValue:headerRangeFieldValue forHTTPHeaderField:@"Range"];    }    downloadOperation.outputStream = [NSOutputStream outputStreamToFileAtPath:DOWNLOADED_PART_FILE_PATH append:YES];    [downloadOperation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {        NSLog(@"%lld/%lld", totalBytesRead + downloadedPartFileSize, totalBytesExpectedToRead + downloadedPartFileSize);    }];    [downloadOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {        NSLog(@"downloadOperation completion block invoked");    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {        NSLog(@"downloadOperation failure block invoked");    }];    //  将单个下载任务加入到下载队列当中    [downloadOperationQueue addOperation:downloadOperation];    //  暂停某下载任务    [downloadOperation pause];    //  继续某下载任务    [downloadOperation resume];    //  取消某下载任务(同时应将其已下载部分的文件删除)    [downloadOperation cancel];    [[NSFileManager defaultManager] removeItemAtPath:DOWNLOADED_PART_FILE_PATH error:&error];    //  取消全部下载任务    [downloadOperationQueue cancelAllOperations];    //  此外还有若干方法用以判断相应一见其名便知其义的状态...    downloadOperation.isReady    downloadOperation.isExecuting    downloadOperation.isPaused    downloadOperation.isCancelled    downloadOperation.isFinished    //  判断downloadOperation是否存在在downloadOperationQueue当中    [downloadOperationQueue.operations containsObject:downloadOperation]




0 0