2013-12-11 5 views
0

Я загружаю файл с AFNetworking, используя этот код:Удалить незавершенный загруженный файл, если загрузка будет отменена

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:downloadFileUrl]]; 

AFHTTPRequestOperation * operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 

NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString * documentDirectory = [paths objectAtIndex:0]; 

NSString * targetFileName = [downloadFileUrl lastPathComponent]; 
NSString * targetPath = [documentDirectory stringByAppendingPathComponent:targetFileName]; 

operation.outputStream = [NSOutputStream outputStreamToFileAtPath:targetPath append:NO]; 

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 

    [[NSNotificationCenter defaultCenter] postNotificationName:@"DownloadDidSuccessNotification" object:nil]; 

} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 

    [[NSNotificationCenter defaultCenter] postNotificationName:@"DownloadDidFailedNotification" object:nil]; 

}]; 

[operation start]; 

Я предоставляю возможность для пользователя, чтобы отменить загрузку, я сделать это следующим образом:

[operation cancel]; 

Однако незавершенный загруженный файл остается в каталоге. Пожалуйста, дайте мне знать решение для удаления незавершенного загруженного файла.

+1

Во время отмены операции загрузки или операции загрузки вы можете получить путь к файлу и удалить его из каталога. –

ответ

3

Попробуйте этот код. Я не проверял.

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 

    [[NSNotificationCenter defaultCenter] postNotificationName:@"DownloadDidSuccessNotification" object:nil]; 

} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
     NSFileManager *fileMgr = [NSFileManager defaultManager] ; 
     NSError *error = nil; 
    BOOL removeSuccess = [fileMgr removeItemAtPath:targetPath error:&error]; 
     if (!removeSuccess) { 
      // Error handling 
      ... 
     } 
    [[NSNotificationCenter defaultCenter] postNotificationName:@"DownloadDidFailedNotification" object:nil]; 

}]; 
2

Попробуйте удалить файл -

NSArray *searchPaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

NSString *documentFolderPath = [searchPaths objectAtIndex:0]; 
BOOL success=[[NSFileManager defaultManager] fileExistsAtPath: targetPath]; 
if (success) 
{ 
     BOOL deletedFile = [[NSFileManager defaultManager] removeItemAtPath: targetPath error:&error]; 
    if (deletedFile) 
     NSLog(@"File deleted"); 
    else 
     NSLog(@"Not able to delete File"); 
}