ok after more than 10 days of attempts and failures, I found a solution, first of all, there are two scenarios of the case when the user closes the application and there is an active download in the background, please note that for these cases the download task is never intended to resume.
1. When the user closes the application, but is still active, it calls - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error , and the temporary file that was used to download directly gets to the temp directory of the application, in this case - (void)applicationWillTerminate:(UIApplication *)application , but the delegate of the download task is called the first. The solution is to implement code to clean the temp directory every time the application is open or let iOS clear the temporary folder, this is explained here when iOS is about to clear the temporary file:
When iOS cleans up directories on-premises / tmp?
2. When the user closes the application in the background, the application is terminated, and the next time the application is opened, it calls - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error , and the temporary file that used for download, stored in NSCachesDirectory in the following directory:
var/mobile/Containers/Data/Application/CA21-B6E8-3305A39/Library/Caches/com.apple.nsurlsessiond/Downloads/com.xxx.xxx/CFNetworkDownload_M5o8Su.tmp
The temporary file will be moved to the temporary directory of the application at the next boot.
the solution here is to implement the code to delete all temporary files from Caches/com.apple.nsurlsessiond/Downloads/com.xxx.xxx/ as soon as it starts - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error .
Here is the code to remove temporary 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 since it only works for this scenario, it’s best to implement code to clear the application’s temporary directory each time it starts, or let iOS clear the temporary folder so that it works for both scenarios.
Here is the code on how to clear the temporary directory of the application:
NSString *path = NSTemporaryDirectory(); NSArray *array = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil]; for (NSString *string in array) { [[NSFileManager defaultManager] removeItemAtPath:[path stringByAppendingPathComponent:string] error:nil]; }