我需要使用我的iPad应用程序下载大型.zip文件(最多800 MB)。 如果取消下载或应用程序在后台,我想再次恢复下载。
operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:YES];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject){
// unzip the .zip
}failure:^(AFHTTPRequestOperation *operation, NSError *error){
//Handle the error
}];
[operation setDownloadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten,long long totalBytesExpectedToWrite) {
//update the progressView
}];
[operation setShouldExecuteAsBackgroundTaskWithExpirationHandler:^{
// What I have to do here?
}];
[operation start];
[operation waitUntilFinished];
-(void)applicationWillResignActive:(UIApplication *)application{
// What I have to do here?
}
感谢您的帮助。
答案 0 :(得分:23)
您可以使用AFDownloadRequestOperation执行此操作。
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"....zip"]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"....zip"];
AFDownloadRequestOperation *operation = [[AFDownloadRequestOperation alloc] initWithRequest:request targetPath:path shouldResume:YES];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Successfully downloaded file to %@", path);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
[operation setProgressiveDownloadProgressBlock:^(NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile) {
NSLog(@"Operation%i: bytesRead: %d", 1, bytesRead);
NSLog(@"Operation%i: totalBytesRead: %lld", 1, totalBytesRead);
NSLog(@"Operation%i: totalBytesExpected: %lld", 1, totalBytesExpected);
NSLog(@"Operation%i: totalBytesReadForFile: %lld", 1, totalBytesReadForFile);
NSLog(@"Operation%i: totalBytesExpectedToReadForFile: %lld", 1, totalBytesExpectedToReadForFile);
}];
[operations addObject:operation];
重新启动应用程序并生成具有相同网址的请求后,它将继续下载。 " shouldResume:YES"作品