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

為{幸葍}努か 提交于 2019-12-05 10:21:39

I have recently come across the same issue. I have found that the response is save to a file in the Cache Directory which will be locked due to the user having a password. You need to run this somewhere in the app before you create the session.

  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];

Just a quick translation of James' answer to 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)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!