廢話不說直接上代碼
import UIKit
import LocalAuthentication
class FingerprintVerifyManager {
//單例實現(xiàn)
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)
}
}
//驗證出現(xiàn)錯誤
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)")
}
}