Exploring Touch Id with Xamarin

With the release of iOS 8, came a bevy of new APIs. One of my favorites is access to the Touch Id sensor. Many feature apps already have stared using this in their apps (Amazon, Mint, and my personal favorite 1Password). Xamarin offers day one support of native APIs, so I thought I would explore how to use this feature in c#.

Let's make a quick app

I wanted to try out the Xamarin iOS Designer that I saw demonstrated at Evolve (videos should be up soon). So I started with a Single View Application.

image of new project screen

Let's add a message to display to authenticated users who might just need a bit of reassurance in their lives, as well as a button to display the touch id dialog.

image of storyboard This message (spelling problems included) comes from one of my favorite apps to ever be released to the appstore, I am Rich, which I saw when I upgraded my original iPhone on day one.

In the code behind the view, we add a reference to LocalAuthentication. This exposes the touch id API.

using LocalAuthentication;

Hide the message label.

messageLbl.Hidden = true;

And now we wire the button to do the following on click.

 revealButton.TouchUpInside += async(s, e) =>
        {
            var context = new LAContext();
            var error = new NSError();

            if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out error))
            {
                var authenticated = await context.EvaluatePolicyAsync(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, 
                        "Authenticate to see secret message");
                if (authenticated)
                {
                    messageLbl.Hidden = false;
                }
            }

        };

As of this writing, the Xamarin Documentation has a bug, because the framework expects 'error' to be an out parameter. Easy fix.

And voila, you now have a functioning app that will display your message if you authenticate with touch id.

image of touch id dialog image of message showing

Now what if we don't have touch id?

It was very simple to get this demo working, but it wasn't very practical, as not every iDevice has touch id, and some people might choose to opt out or are unable to authenticate. This is very easy to work around with Xamarin iOS.

Add a try / catch to the TouchUpInside handler to handle a situation where there an exception (anything but valid touch authentication appears to throw an exception). Cast the NSErrorException to the LAStatus enum. Then you can do whatever you want if there is an error or the user doesn't have touch id or wants to type in a password.

 revealButton.TouchUpInside += async(s, e) =>
        {
            var context = new LAContext();

            var error = new NSError();
            try
            {
                var authenticated = await context.EvaluatePolicyAsync(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, 
                                            "Authenticate to see secret message");
                if (authenticated)
                {
                    messageLbl.Hidden = false;
                }
            }
            catch (NSErrorException ex)
            {
                var reason = Convert.ToInt16(ex.Code);
                var status = (LAStatus)reason;
                ShowUnauthorizedAlert(status.ToString());
            }
        };
    }

    private void ShowUnauthorizedAlert(string reason)
    {
        var alert = new UIAlertView("Not Allowed", string.Format("You Arent Authorized For This \n Reason: {0}", reason),
            null, "OK", null);
        alert.Show();
    }

In this instance I just show a message relaying the status, but many will show a password view to do another form of authentication, based on the LAStatus

image of alert

And now you are able to have a functioning app that allows for multiple ways to authenticate the user can see the reassuring message of self worth.

in summary

In this post, we reviewed how to use the touch id api given to us in iOS 8 using Xamarin tools. The code for this sample is available here. Thanks!

updated to include how to get the status from the touch id dialog!

comments powered by Disqus