我的应用程序已打开数据保护,并使用NSFileProtectionComplete创建了一个文件

+ (void)createLogFile {
    NSString *deviceModel = [Utils getDeviceModel];
    NSString *appVersion = [Utils getAppVersion];
    NSData *initData = [[NSString stringWithFormat:@"%@-%@\n================================\n\n\n", deviceModel, appVersion] dataUsingEncoding:NSUTF8StringEncoding];
   [[NSFileManager defaultManager] createFileAtPath:[self logFilePath]
                                        contents:initData
                                      attributes:@{NSFileProtectionKey: NSFileProtectionComplete}];
}

当我锁定设备时,applicationProtectedDataWillBecomeUnavailable:将被调用。
- (void)applicationProtectedDataWillBecomeUnavailable:(UIApplication *)application {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSData *key = [MyKeychain getKey];
        NSString *log = [NSString stringWithFormat:@"The key is:\n %@", key];
        [MyFileLogger logInfo:log];
    });
}

然后,我可以在文件中找到结果,这意味着我可以在设备锁定时写入该文件。
设备锁定时,Data Protection不应阻止访问文件吗?怎么了?

--updated--(添加方法logInfo :)
+ (void)logInfo:(NSString *)str {
    NSString *info = [self wrapWithTimestamp: str];
    NSString *logFilePath = [Utils logFilePath];
    if (![[NSFileManager defaultManager] fileExistsAtPath:logFilePath]) {
        [Utils createLogFile];
    }
    NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:logFilePath];
    [handle truncateFileAtOffset:[handle seekToEndOfFile]];
    [handle writeData:[info dataUsingEncoding:NSUTF8StringEncoding]];
    [handle closeFile];
}

最佳答案

根据对this question的回答,在调用applicationProtectedDataWillBecomeUnavailable方法之后,在激活数据保护之前有10秒的“宽限期”。

如果您将时间延迟从5秒增加到11秒,则应该看到您的数据未写入日志文件。

我能够通过示例代码和11秒的延迟观察到这一点。

10-05 20:26
查看更多