我有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];
答案 0 :(得分: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];
答案 1 :(得分:0)
快速翻译一下詹姆斯对Swift 4的回答
if let plist = Bundle.main.path(forResource: "Info", ofType: "plist"),
let dict = NSDictionary(contentsOfFile: plist) as? [String: AnyObject],
var path = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first,
let bundle = dict["CFBundleIdentifier"] {
path.append("/Caches/com.apple.nsurlsessiond/Downloads/\(bundle)")
try? FileManager.default.setAttributes([FileAttributeKey.protectionKey: FileProtectionType.completeUntilFirstUserAuthentication], ofItemAtPath: path)
}