[英]Touch Id with Xamarin Forms Application
我們正在嘗試通過Xamarin Forms應用程序在iOS上使用Touch ID。
在我們的Xamarin Forms應用程序中,在App.Xaml.cs構造函數中,我們使用一個接口來引用iOS本機touch id實現:
bool _authenticatedWithTouchID = DependencyService.Get<ITouchID>().AuthenticateUserIDWithTouchID();
if (_authenticatedWithTouchID)
{
MainPage = new NavigationPage(new MainPage());
}
else
{
MainPage = new NavigationPage(new LoginPage());
}
這是Forms Application中的接口簽名:
public interface ITouchID
{
bool AuthenticateUserIDWithTouchID();
}
這是iOS項目中接口的實現:
[assembly: Dependency(typeof(TouchID))]
namespace GetIn.iOS
{
public class TouchID : ITouchID
{
public bool AuthenticateUserIDWithTouchID()
{
bool outcome = false;
var context = new LAContext();
if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out NSError AuthError))
{
var replyHandler = new LAContextReplyHandler((success, error) => {
Device.BeginInvokeOnMainThread(() => {
if (success)
{
outcome = true;
}
else
{
outcome = false;
}
});
});
context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, "Logging with touch ID", replyHandler);
};
return outcome;
}
}
}
我們從結果變量中得到一個響應(如果用戶已通過身份驗證,則為true),但不會將其傳遞回Forms應用程序。
我們也嘗試使用沒有運氣的異步任務。
有沒有推薦的方法來做到這一點? 我們正在努力使這一過程盡可能簡單。
您需要更改代碼以處理異步行為。
public class TouchID : ITouchID
{
public Task<bool> AuthenticateUserIDWithTouchID()
{
var taskSource = new TaskCompletionSource<bool>();
var context = new LAContext();
if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out NSError AuthError))
{
var replyHandler = new LAContextReplyHandler((success, error) => {
taskSource.SetResult(success);
});
context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, "Logging with touch ID", replyHandler);
};
return taskSource.Task;
}
}
記住在上面添加using
using System.Threading.Tasks;
並更改您的接口聲明
public interface ITouchID
{
Task<bool> AuthenticateUserIDWithTouchID();
}
最后是您的Xamarin.Forms代碼...
var touchId = DependencyService.Get<ITouchID>();
var _authenticatedWithTouchID = await touchId.AuthenticateUserIDWithTouchID();
if (_authenticatedWithTouchID)
{
MainPage = new NavigationPage(new MainPage());
}
else
{
MainPage = new NavigationPage(new LoginPage());
}
通過使用上面的異步更改(盡管您可以在不使用異步方法的情況下執行此操作),然后執行以下操作來設法使其正常工作:
通過將以下代碼從app.xaml.cs移至我們的MainPage.xaml.cs(我們的選項卡式頁面)構造函數中,並將其改編為MainPage.xaml.cs(我們的選項卡式頁面)構造函數。
var touchId = DependencyService.Get<ITouchID>();
var _authenticatedWithTouchID = await
touchId.AuthenticateUserIDWithTouchID();
if (_authenticatedWithTouchID)
{
//Do Nothing as on this page
}
else
{
//Go back to login page
Navigation.InsertPageBefore(new LoginPage(), this);
await Navigation.PopAsync();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.