ios - 设备锁定时在 Today 扩展中加载文件

标签 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
    }
}

最佳答案

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

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);
}

在许多情况下,您通常不希望这样做,但由于这些信息旨在从锁定屏幕查看,所以我同意删除文件保护。

关于ios - 设备锁定时在 Today 扩展中加载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25938178/

相关文章:

ios - Swift 中使用 SKSpriteNode 进行水平无限滚动

iphone - UITableViewCell 在编辑模式下移动时显示两个不同的项目

ios - 如何使用 NSUserDefaults 与 Today 扩展共享数据(自定义对象数组)?

swift - 在不影响老用户的情况下更新代码流

ios - 如何使用 FileManager 检索嵌套文件?

android - 我应该在 Firestore 的字段文档中只写标识符还是写所有数据?

ios - Firebase 获取 child ID swift ios

swift - 如何在多次点击时删除节点

ios - 将所有捆绑资源复制到 Documents 目录内的单独文件夹中

ios - 下载的图像在文档目录中有零字节