废话不说直接上代码
import UIKit
import LocalAuthentication
class FingerprintVerifyManager {
//单例实现
static let instance = FingerprintVerifyManager()
private init(){}
//验证完的闭包回调
typealias TouchIdVerify = (isSuccess:Bool, error:NSError?) ->()
//调用指纹验证
func touchIdWithHand(identtyVerify:TouchIdVerify) {
let version = UIDevice.currentDevice().systemVersion
let result = version.compare("8.0.0")
assert(result == NSComparisonResult.OrderedDescending, "IOS8.0以上可使用")
let context = LAContext()
let resultMsg = "验证指纹密码"
//设备验证
let (deviceVerify, error) = checkIsOpenFingerprintVerify()
if deviceVerify {
context.evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason: resultMsg, reply: { (isSuccess, error) -> Void in
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
identtyVerify(isSuccess: isSuccess, error: error)
})
})
}else {
print("失败\(error!.code)")
deviceVerifyWithError(error)
}
}
//验证出现错误
func deviceVerifyWithError(error:NSError!) {
switch error!.code {
case Int(kLAErrorTouchIDNotEnrolled):
print("\(kLAErrorTouchIDNotEnrolled)")
print("设备支持,但用户没有设置")
break;
case Int(kLAErrorPasscodeNotSet):
print("\(kLAErrorPasscodeNotSet)")
print("设备支持,但是被禁用")
break;
default:
print("设备不支持")
break;
}
}
//设备是否打开/支持指纹验证
func checkIsOpenFingerprintVerify() -> (isopen:Bool, error:NSError?) {
let context = LAContext()
var error:NSError?
let isOpen = context.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error: &error)
return (isOpen, error)
}
}
调用
@IBAction func fingerprintVerify(sender: AnyObject) {
let finerVerify = FingerprintVerifyManager.instance
finerVerify.touchIdWithHand { (isSuccess, error) -> () in
print("success:\(isSuccess), error:\(error?.code)")
}
}