Use Swift to determine if device has passcode set
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// PasscodeUtils.swift | |
// | |
// Created by Ben Bahrenburg on 12/31/16. | |
// Copyright © 2016 bencoding.com. All rights reserved. | |
// | |
import Foundation | |
import LocalAuthentication | |
public final class PasscodeUtils { | |
fileprivate var context = LAContext() | |
@available(iOS 8.0, *) | |
private func devicePasscodeEnabledUsingKeychain() -> Bool { | |
let query: [String:Any] = [ | |
kSecClass as String : kSecClassGenericPassword, | |
kSecAttrAccount as String : UUID().uuidString, | |
kSecAttrAccessible as String: kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly, | |
kSecValueData as String: "HelloWorld".data(using: String.Encoding.utf8)!, | |
kSecReturnAttributes as String : kCFBooleanTrue | |
] | |
var dataTypeRef: AnyObject? | |
var status = withUnsafeMutablePointer(to: &dataTypeRef) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0)) } | |
if status == errSecItemNotFound { | |
let createStatus = SecItemAdd(query as CFDictionary, nil) | |
guard createStatus == errSecSuccess else { return false } | |
status = withUnsafeMutablePointer(to: &dataTypeRef) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0)) } | |
} | |
guard status == errSecSuccess else { return false } | |
return true | |
} | |
public func devicePasscodeEnabled() -> Bool { | |
if #available(iOS 9.0, *) { | |
return context.canEvaluatePolicy(.deviceOwnerAuthentication, error: nil) | |
} else { | |
return devicePasscodeEnabledUsingKeychain() | |
} | |
} | |
@available(iOS 8.0, *) | |
public func deviceBiometricsEnabled() -> Bool { | |
return context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment