当设备被锁定时,在Today扩展中加载文件

时间:2014-09-19 16:09:59

标签: ios swift nsfilemanager today-extension

在我的设备解锁的今天扩展中,这行代码按预期工作,从图像路径返回数据:

let imageData = NSData(contentsOfFile: path)

但是当我的设备被密码锁定时,它返回nil。设备锁定时,有没有办法访问文件系统中的图像?我可以很好地访问UserDefaults,但不能访问我的共享组目录中的文件。以下是我创建路径的方法,调用imagePath,在两种情况下都正确填充了我期望的路径:

func rootFilePath() -> String? {
    let manager = NSFileManager()
    let containerURL = manager.containerURLForSecurityApplicationGroupIdentifier(GROUP_ID)
    if let unwrappedURL = containerURL {
        return unwrappedURL.path
    }
    else {
        return nil
    }
}

func imagePath() -> String? {
    let rootPath = rootFilePath()
    if let uPath = rootPath {
        return "\(uPath)/\(imageId).png"
    }
    else {
        return nil
    }
}

1 个答案:

答案 0 :(得分:0)

我刚想通了!您需要相应地设置文件权限:

NSFileManager *fm = [[NSFileManager alloc] init];
NSDictionary *attribs = @{NSFileProtectionKey : NSFileProtectionNone};
NSError *unprotectError = nil;

BOOL unprotectSuccess = [fm setAttributes:attribs
                             ofItemAtPath:[containerURL path]
                                    error:&unprotectError];
if (!unprotectSuccess) {
    NSLog(@"Unable to remove protection from file! %@", unprotectError);
}

在许多情况下,您通常不想这样做,但由于要从锁定屏幕查看信息,我可以删除文件保护。