BackgroundSession SessionDownloadTask在锁定屏幕时,错误:NSPOSIXErrorDomain Code = 1

Jim*_*mBo 5 download ios nsurlsessiondownloadtask

我有NSURLSessionDownloadTask一个backgroundSessionConfigurationWithIdentifier.当我锁定屏幕时,会发生以下异常:

错误域= NSPOSIXErrorDomain代码= 1"操作无法完成操作不允许.".

此错误仅在我的手机上发生,它不会出现在其他手机上.

下面是简单的代码:

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];
Run Code Online (Sandbox Code Playgroud)

小智 5

我最近遇到过同样的问题.我发现响应被保存到缓存目录中的文件,由于用户有密码,该文件将被锁定.在创建会话之前,您需要在应用程序中的某个位置运行它.

  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];
Run Code Online (Sandbox Code Playgroud)