在你的应用中添加 Touch ID
首先,确定设备是否能够接受 Touch ID 输入。
if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError))
如果是,那么我们可以使用以下方式显示 Touch ID UI:
context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, myReason, replyHandler);
我们必须将三条信息传递给 EvaluatePolicy
- 策略本身,一个解释为什么需要身份验证的字符串,以及一个回复处理程序。回复处理程序告诉应用程序在成功或不成功的身份验证的情况下应该做什么。
本地身份验证的一个注意事项是它必须在前台运行,因此请确保使用 InvokeOnMainThread
作为回复处理程序:
var replyHandler = new LAContextReplyHandler((success, error) =>
{
this.InvokeOnMainThread(() =>
{
if (success)
{
Console.WriteLine("You logged in!");
PerformSegue("AuthenticationSegue", this);
}
else {
//Show fallback mechanism here
}
});
});
要确定是否已修改授权指纹数据库,你可以检查 context.EvaluatedPolicyDomainState
返回的不透明结构(NSData)。你的应用需要存储并比较策略状态以检测更改。有一点需要注意,Apple 指出:
但是,无法根据此数据确定更改的性质。
if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError))
{
var policyState = context.EvaluatedPolicyDomainState;
var replyHandler = new LAContextReplyHandler((success, error) =>
{
this.InvokeOnMainThread(() =>
{
if (success)
{
Console.WriteLine("You logged in!");
PerformSegue("AuthenticationSegue", this);
}
else {
//Show fallback mechanism here
}
});
});
context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, myReason, replyHandler);
};
按钮示例
partial void AuthenticateMe(UIButton sender)
{
var context = new LAContext();
//Describes an authentication context
//that allows apps to request user authentication using Touch ID.
NSError AuthError;
//create the reference for error should it occur during the authentication.
var myReason = new NSString("To add a new chore");
//this is the string displayed at the window for touch id
if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError))
// check if the device have touchId capabilities.
{
var replyHandler = new LAContextReplyHandler((success, error) =>
{
this.InvokeOnMainThread(() =>
{
if (success)
{
Console.WriteLine("You logged in!");
PerformSegue("AuthenticationSegue", this);
}
else {
//Show fallback mechanism here
}
});
});
context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, myReason, replyHandler);//send touch id request
};
}