我们正在尝试使用Xamarin表单应用程序与iOS使用触摸ID。
在我们的Xamarin Forms应用程序中,在App.xaml.cs构造函数中,我们使用接口来引用iOS本机触摸ID实现:
bool _authenticatedWithTouchID = DependencyService.Get<ITouchID>().AuthenticateUserIDWithTouchID();
if (_authenticatedWithTouchID)
{
MainPage = new NavigationPage(new MainPage());
}
else
{
MainPage = new NavigationPage(new LoginPage());
}
这是表单应用程序中的接口签名:
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;
}
}
}
我们从结果变量中获得响应(如果用户被认证,这是正确的(,但这并未传递回表单应用程序。
我们还尝试使用没有运气的异步任务。
有建议的方法我们这样做吗?我们正在尝试使其尽可能简单。
您需要更改代码以处理异步行为。
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;
}
}
请记住添加top
上的使用
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(我们的选项卡式页面(构造函数。
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();
}