2014-03-27 46 views
3

我们有一个存储敏感数据的应用程序。我们启用了文件保护功能,但只有在用户设置了密码时才有效。如果用户没有设置密码,我们需要显示一条警告,告诉用户这样做,然后不加载应用程序的其余部分。我可以检查用户是否设置了密码?

基本上我们的确切情况与this question一样,我的问题恰好是他们的问题。但是接受的答案是“启用文件保护”,这不是对这个问题的答案,或者对这个问题的答案;我已经启用了文件保护功能,但并没有告诉我他们是否设置了密码。

那么有可能检查,如果是的话,怎么样?理想情况下,我们希望检查用户是否设置了长密码或简单的密码,如果他们只设置了简单的密码,我们会警告他们设置适当的密码。

回答

3

使用iOS 8,现在有一种方法可以检查用户是否设置了密码。 该代码会崩溃在iOS 7

的Objective-C:

-(BOOL) deviceHasPasscode { 
    NSData* secret = [@"Device has passcode set?" dataUsingEncoding:NSUTF8StringEncoding]; 
    NSDictionary *attributes = @{ (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword, (__bridge id)kSecAttrService: @"LocalDeviceServices", (__bridge id)kSecAttrAccount: @"NoAccount", (__bridge id)kSecValueData: secret, (__bridge id)kSecAttrAccessible: (__bridge id)kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly }; 

    OSStatus status = SecItemAdd((__bridge CFDictionaryRef)attributes, NULL); 
    if (status == errSecSuccess) { // item added okay, passcode has been set    
     SecItemDelete((__bridge CFDictionaryRef)attributes); 

     return true; 
    } 

    return false; 
} 

斯威夫特:

func deviceHasPasscode() -> Bool { 
    let secret = "Device has passcode set?".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) 
    let attributes = [kSecClass as String:kSecClassGenericPassword, kSecAttrService as String:"LocalDeviceServices", kSecAttrAccount as String:"NoAccount", kSecValueData as String:secret!, kSecAttrAccessible as String:kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly] 

    let status = SecItemAdd(attributes, nil) 
    if status == 0 { 
     SecItemDelete(attributes) 
     return true 
    } 

    return false 
} 
+0

它在iOS 11(beta)上工作吗?我们正面临iOS 11(beta) –

7

有一个官方的回答这个问题与iOS 9:

LAContext *myContext = [[LAContext alloc] init]; 
NSError *authError = nil; 

if ([myContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthentication error:&authError]) 
{ 
    // Device has either passcode enable (or passcode and touchID) 
} 
else 
{ 
    // Device does not have a passcode 
    // authError can be checked for more infos (is of type LAError) 
} 

指向Apple's LAContext class的链接

注意:LAPolicyDeviceOwnerAuthentication是仅在iOS 9中可用的常量。 iOS 8已有LAPolicyDeviceOwnerAuthenticationWithBiometrics可用。它可以用来实现一些结果,但这些不能回答你的问题。

+0

好问题,适用于iOS10。在Swift3中同样的东西:'func deviceHasPasscodeEnabled() - > Bool { let myContext = LAContext() var authError:NSError? =零 如果(myContext.canEvaluatePolicy(.deviceOwnerAuthentication,错误:authError)){ 回报 真正 } 其他 { 返回假 } }' – JBA

相关问题