在你的應用中新增 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
    };
}