如何在iOS 10中使用TouchID
问题描述:
我想在我的iOS应用程序中实现本地身份验证安全性,但我是 出现错误,无法弄清楚为什么我得到这个。如何在iOS 10中使用TouchID
我正在使用iPhone 5s。这很重要吗?
码:
import UIKit
import LocalAuthentication
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func action(_ sender: Any) {
authenticateUser()
}
func authenticateUser() {
let authContext : LAContext = LAContext()
var error: NSError?
if authContext.canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error: &error){
authContext.evaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, localizedReason: "Biometric Check for application", reply: {(successful: Bool, error: NSError?) -> Void in
if successful{
print("TouchID Yes")
}
else{
print("TouchID No")
}
} as! (Bool, Error?) -> Void)
}
else{
authContext.evaluatePolicy(LAPolicy.deviceOwnerAuthentication, localizedReason: "Enter your Passcode", reply: {
(successful: Bool, error: NSError?) in
if successful{
print("PassCode Yes")
}
else{
print("PassCode No")
}
} as! (Bool, Error?) -> Void)
}
}
}
错误:
在此先感谢。
答
没有强制类型转换此代码应该工作
func authenticateUser() {
let authContext : LAContext = LAContext()
var error: NSError?
if authContext.canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error: &error){
authContext.evaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, localizedReason: "Biometric Check for application", reply: {successful, error -> Void in
if successful{
print("TouchID Yes")
}
else{
print("TouchID No")
}
}
)
}
else{
authContext.evaluatePolicy(LAPolicy.deviceOwnerAuthentication, localizedReason: "Enter your Passcode", reply: {
successful,error in
if successful{
print("PassCode Yes")
}
else{
print("PassCode No")
}
}
)
}
}
请解释为什么这能解决问题:这是因为你不能类型转换封闭,因为这是毫无意义的。 –
这不是将NSError转换为错误,因为这不是你在演员时所做的。封闭是一种类型,而向不相关类型倾倒的力量总是会失败。 '12! String'会抛出一个异常。类似地,当你强迫将((Bool,NSError?) - > Void)'向下变为无关类型'((Bool,Error?) - > Void)'时,你会得到一个异常。仅仅因为NSError和Error是相关的,并不会使与不同签名相关的闭包。 – Paulw11