1

My app has turned on Data Protection and I created a file with 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}];
}

and when I lock my device applicationProtectedDataWillBecomeUnavailable: will be called.

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

Then I can find the result in the file, which means I was able to write that file when my device is locked. Shouldn't Data Protection prevents from accessing files when device is locked? What's wrong?

--updated-- (add method 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];
}
Benson
  • 248
  • 3
  • 15

1 Answers1

1

According to the answer to this question, after the applicationProtectedDataWillBecomeUnavailable method is called there is a 10 second "grace period" before data protection activates.

If you increase your time delay from 5 to 11 seconds you should see that your data is not written to your log file.

I was able to observe this with sample code and an 11 second delay.

Paulw11
  • 108,386
  • 14
  • 159
  • 186