Implementing and Testing iOS data protection

前端 未结 7 1440
傲寒
傲寒 2020-11-28 05:20

Just saw the Session 209 - Securing Application Data from de 2010 WWDC.

The keynote explains a lot of things, including the way you can set data protection attribute

7条回答
  •  清歌不尽
    2020-11-28 05:56

    File protection can be enabled on a per-file or per-directory basis, or can be enabled for the whole application (using entitlements and the provisioning profile). To determine if a file or directory is protected, check the filesystem attributes for the data protection key. This should be valid even it's a parent directory that was set to be protected:

    - (BOOL) isProtectedItemAtURL:(NSURL *)URL {
        BOOL            result                      = YES;
        NSDictionary    *attributes                 = nil;
        NSString        *protectionAttributeValue   = nil;
        NSFileManager   *fileManager                = nil;
    
        fileManager = [[NSFileManager alloc] init];
        attributes = [fileManager attributesOfItemAtPath:[URL path] error:&error];
        if (attributes != nil){
            protectionAttributeValue = [attributes valueForKey:NSFileProtectionKey];
            if ((protectionAttributeValue == nil) || [protectionAttributeValue isEqualToString:NSFileProtectionNone]){
                result = NO;
            }
        } else {
            // handle the error
        }
        return result;
    }
    

    To determine if the protected content is available, UIApplication provides a method for querying the protection state, isProtectedDataAvailable. Using it with the above method would allow you to determine wether a particular file or directory is available:

    - (BOOL) isItemAtURLAvailable:(NSURL *)URL {
        BOOL            result                      = NO;
    
        if ([self isProtectedItemAtURL:URL]){
            // Item is protected
            if ([[UIApplication sharedApplication] isProtectedDataAvailable]){
                // Protected content is available
                result = YES;
            }
        } else {
            result = YES;
        }
    
        return result;
    }
    

提交回复
热议问题