Skip to content

Instantly share code, notes, and snippets.

@benbahrenburg
Last active July 8, 2020 13:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benbahrenburg/199051c09b194b63ef8b34fd6457d861 to your computer and use it in GitHub Desktop.
Save benbahrenburg/199051c09b194b63ef8b34fd6457d861 to your computer and use it in GitHub Desktop.
Use Swift to determine if device has passcode set
//
// 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