BackgroundSession SessionDownloadTask when locking the screen, Error: NSPOSIXErrorDomain Code = 1

I have an NSURLSessionDownloadTask with backgroundSessionConfigurationWithIdentifier . When I lock the screen, this exception occurs:

Domain Error = NSPOSIXErrorDomain Code = 1 "Operation cannot be completed. Operation not allowed.".

This error occurs only on my phone, it does not appear on other phones.

below is a simple code:

 NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.edu.downLoadTest"];; AFURLSessionManager *_session = [[AFURLSessionManager alloc] initWithSessionConfiguration:sessionConfiguration]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://podcasts.apple.com/apple_keynotes_hd/2015/2015_mar_hd_cc.m4v"]]; NSProgress *progress; NSURLSessionDownloadTask *task1 = [_session downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { NSString *a =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; return [NSURL fileURLWithPath:[a stringByAppendingPathComponent:@"test.m4v"]]; } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { NSLog(@"%@",error); }]; [task1 resume]; 
+3
source share
1 answer

I recently ran into the same problem. I found that the response is stored in a file in the Cache directory, which will be blocked due to the user having a password. Before creating a session, you need to run this somewhere in the application.

  NSString* path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]; path = [path stringByAppendingPathComponent:@"Caches/com.apple.nsurlsessiond/Downloads"]; NSString *appInfoPlist = [[NSBundle mainBundle] pathForResource:@"Info" ofType:@"plist"]; NSDictionary *dictionary = [[NSDictionary alloc]initWithContentsOfFile:appInfoPlist]; path = [path stringByAppendingPathComponent:dictionary[@"CFBundleIdentifier"]]; [[NSFileManager defaultManager] setAttributes:@{NSFileProtectionKey: NSFileProtectionCompleteUntilFirstUserAuthentication} ofItemAtPath:path error:nil]; 
+4
source

Source: https://habr.com/ru/post/975136/


All Articles