Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSURLSessionDownloadTask not deleting the file when the app is closed by the user and the task was still active

I have a NSURLSession and a NSURLSessionDownloadTask configured for downloading a file in background, if the download task in canceled by the user all the data is deleted and the storage space the file was using is freed, but if the app is closed from the multitasking dock the download task is terminated and gives an error but is not deleting the data and the temporal data for the file is still occupying storage space and is never freed. What do i need to do in order to free the space ?

This is my NSURLSession configuration and error handling:

- (NSURLSession *)backgroundSession {
    static NSURLSession *session = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        NSURLSessionConfiguration *configuration;
        if ([[UIDevice currentDevice].systemVersion hasPrefix:@"7"]) configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.visyon.pr"];
        else configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.visyon.pr"];
        configuration.sessionSendsLaunchEvents =YES;

        session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];

    });
    return session; }


- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {


if (error == nil) {
    NSLog(@"Task: %@ completed successfully", task );
} else {
   // [self hideActivity];
   // [self showAlertBoxErrorDownload];
    NSLog(@"Task: %@ completed with error: %@, %lu", task, [error localizedDescription], (long)error.code);

}    self.downloadTask = nil; }
like image 490
user1241006 Avatar asked Jul 28 '15 16:07

user1241006


1 Answers

ok after more than 10 days of try and fail I found the solution, first of all there are two case scenarios when the user close the app and there is an active download in background, please take in to account that for this cases the download task is never intended to be resumed.

scenario 1. when the user close the app but is still active, the - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error is called and the temporal file that was using for the download goes directly to the temp directory of the app, in this case the - (void)applicationWillTerminate:(UIApplication *)application is called but the delegate of the download task is called first. The solution is this case is to implement code to clean the temp directory every time the app is opened or let iOS to clean the temp folder, it is explained here when iOS is going to clean the temp file:

When does iOS clean the local app ./tmp directories?

scenario 2. when the user close the app in background mode the app is terminated and the next time the app is opened the - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error is called and the temporal file that was using for the download is stored in the NSCachesDirectory in the next directory:

var/mobile/Containers/Data/Application/CA21-B6E8-3305A39/Library/Caches/com.apple.nsurlsessiond/Downloads/com.xxx.xxx/CFNetworkDownload_M5o8Su.tmp

The temporal file will be move to the temporal directory of the app the next time there is a new download.

the solution here is to implement code to delete all temporal files from Caches/com.apple.nsurlsessiond/Downloads/com.xxx.xxx/ as soon as the - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error is launched.

Here is the code in order to delete the temporal files from NSCachesDirectory:

    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSArray *array = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[path stringByAppendingPathComponent:@"/com.apple.nsurlsessiond/Downloads/com.xxx.xxx/"] error:nil];
    for (NSString *string in array) {
        [[NSFileManager defaultManager] removeItemAtPath:[path stringByAppendingPathComponent:[NSString stringWithFormat:@"/com.apple.nsurlsessiond/Downloads/com.xxx.xxx/%@",  string]] error:nil];
    }

But because it only work for this scenario its better to implement code to clean the temporal directory of the app every time is launched or let iOS to clean the temp folder so it will work for both scenarios.

Here is the code on how to clean the temporal directory of the app:

NSString *path = NSTemporaryDirectory();
NSArray *array = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
for (NSString *string in array) {
    [[NSFileManager defaultManager] removeItemAtPath:[path stringByAppendingPathComponent:string] error:nil];
}
like image 106
user1241006 Avatar answered Sep 19 '22 20:09

user1241006