我正在使用AFNetworking使用隊列下載一些文件。這裏是我的代碼: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];
}
,並刪除垃圾文件,但不工作的。
您想要刪除垃圾箱或完全下載的文件沒有損壞? –
是的,我確實也嘗試過使用isFinished屬性,但即使我已經取消它們,它仍會繼續下載它們! – zaabalonso