我正在使用AFNetworking使用队列下载一些文件。这是我的代码:
apiClient =[[AFHTTPClient alloc]initWithBaseURL: [NSURL URLWithString:ZFREMOTEHOST]];
for (NSString *element in self.productsArray) {
NSURL *url = [NSURL URLWithString:element];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSString *documentsDirectory = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [paths objectAtIndex:0];
NSString *targetFilename = [url lastPathComponent];
NSString *targetPath = [documentsDirectory stringByAppendingPathComponent:targetFilename];
op.outputStream = [NSOutputStream outputStreamToFileAtPath:targetPath append:NO];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//failure case
NSLog(@"BaaZ File NOT Saved %@", targetPath);
//remove the file if saved a part of it!
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:targetPath error:&error];
if (error) {
NSLog(@"error dude");
}
if ([operation isCancelled]) {
//that doesn't work.
NSLog(@"Canceled");
}
}];
[op setDownloadProgressBlock:^(NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
if (totalBytesExpectedToRead > 0) {
dispatch_async(dispatch_get_main_queue(), ^{
self.progressView.alpha = 1;
self.progressView.progress = (float)totalBytesRead / (float)totalBytesExpectedToRead;
NSString *label = [NSString stringWithFormat:@"Downloaded %lld of %lld bytes", totalBytesRead,totalBytesExpectedToRead];
self.progressLabel.text = label;
});
}
}];
[self.resourcesArray addObject:op];
}
for (AFHTTPRequestOperation *zabols in self.resourcesArray) {
[apiClient.operationQueue addOperation:zabols];
}
代码在文件下载方面工作正常,但我想要一些取消功能,所以我有一个按钮,其动作的代码如下:
[apiClient.operationQueue cancelAllOperations];
操作取消文件但是Documents文件夹上有一些垃圾文件。通过说垃圾我的意思是开始下载的文件我取消了它们并且我得到了一个同名的文件但无法打开因为它被损坏了。
如何阻止AF执行此操作并在取消时仅保留已完成的文件?
任何帮助都会感激不尽。
还尝试按照这样的工作取消工作:
for (AFHTTPRequestOperation *ap in apiClient.operationQueue.operations) {
[ap cancel];
NSLog(@"%@",ap.responseFilePath);
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:ap.responseFilePath error:nil];
}
并删除垃圾文件但不起作用。
答案 0 :(得分:7)
尝试使用AFDownloadRequestOperation扩展名,它还支持恢复部分下载,使用临时目录并有一个特殊的块来帮助计算正确的下载进度。
答案 1 :(得分:-1)
您也可以尝试:github