Category Archives: Xamarin Forms

Xamarin.Forms lifecycle

Note: This post was written a while back but sat in draft. I’ve published this now, but I’m not sure it’s relevant to the latest versions etc. so please bear this in mind.

The following is an example of what’s generated as part of the Xamarin.Forms project.

public class App : Application
{
   protected override void OnStart()
   {
      // Handle when your app starts
   }

   protected override void OnSleep()
   {
      // Handle when your app sleeps
   }

   protected override void OnResume()
   {
      // Handle when your app resumes
   }
}
  • OnStart is called when the application starts
  • OnSleep is called when the application goes into sleep mode and/or terminates
  • OnResume is called when an application is resumed after a sleep

Deploying a Xamarin Forms application to TestFlight

Note: This post was written a while back but sat in draft. I’ve published this now, but I’m not sure it’s relevant to the latest versions etc. so please bear this in mind.

Pre-requisites

You’ll need an Apple developer account if you intend to eventually deploy your application to the Apple store, using this site https://developer.apple.com/account, however you can use the free provisioning using Free provisioning for Xamarin.iOS apps.

As I already have an Apple Developer account this post will concentrate on provisioning with a Developer account id.

TestFlight

TestFlight is the Apple beta testing tool which allows users to access your application in test (i.e. not live on the app store). Your users will need to install TestFlight, see Beta Testing Made Simple with TestFlight and you’ll need to set up an application for testing via https://appstoreconnect.apple.com/

Deploying your application to TestFlight

Once you’ve built and signed your application so it’s ready for distribution then, one of the simplest ways to deploy your application to TestFlight is install Transporter on your Mac and simply Add the application to Transport which in turn will upload to your TestFlight account.

Your application will go through a build process and when completed you’ll receive an email letting you know. You’ll be waiting for the status of your build (within appstoreconnect) to change state to Approved (this may take a couple of days although I’ve also seen posts from people stating this can take longer). Once approved we select our External Groups (testers) and you should see a Enable Public Link – click on this (enable it). Now you’ll have a link to send to your users, although appstoreconnect should automatically send this to any testers you add.

Note: Your TestFlight build is available for a total of 90 days, ofcourse this excludes the build and review process. If you do not update the application within that time the app will expire.

Once your build has passed review, it’ll go into a Testing status, any testers you’ve added already will get a code to redeem in TestFlight from their device, you can also enable a link that you can send to people to load the application for testing. This obviously allows you to have a core group of testers as well as a public access to testing.

When your application is deployed to your testers via TestFlight, the icon that you launch the application from will have a small orange dot (it looks red on a dark background) to indicate this is a beta application.

When you’re ready to update your testers with a new application, if you only change the Build version, i.e. if your app version is 0.1.0 and build was 1.0, just changing this to 2.0 will mean your application need not go through review again. Instead it’ll go into a Submit Ready state, waiting for you to assign testers and then it’ll switch to Testing.

References

Automatic Provisioning for Xamarin.iOS
TestFlight – How to Upload and Distribute Your App | App Store 2021

Device specific code in Xamarin

Note: This post was written a while back but sat in draft. I’ve published this now, but I’m not sure it’s relevant to the latest versions etc. so please bear this in mind.

Occasionally we might need to handle text or UI controls slightly differently on different devices.

In a shared code project we’d probably look to write code using conditional compilation, but this wouldn’t work for PCL code. Also conditional compilation doesn’t work in XAML. So whilst conditional compilation is still a valid technique for shared code projects an alternative is runtime branching based upon the device the code is running on (in other words if or switch code). Xamarin already supplies us with a simple mechanism to achieve this using the OnPlatform method on the Device class.

PCL/Runtime device specific code

So, in code we can use the Device class like this

public class MyPage : ContentPage
{
   public MyPage()
   {
      Padding = Device.OnPlatform(
          new Thickness(0,20,0,0), 
          new Thickness(0),
          new Thickness(0));
   }
}

Or from XAML we can use the OnPlatform element, for example

<ContentPage>
   <ContentPage.Padding>
      <OnPlatform x:TypeArguments="Thickness" iOS="0,20,0,0" />
   </ContentPage.Padding>
</ContentPage>

Conditional Compilation directives

Just to complete the picture, let’s look at what compiler directives exist – these are not exclusive to shared code projects but obviously are available for any use

  • __IOS__ for iOS code
  • __ANDROID__ for Android code
  • __ANDROID_nn__ for Android code, where nn is the Andoird API level supported
  • WINDOWS_UWP for Universal Windows Platform code
  • WINDOWS_APP for Windows 8.1 code
  • WINDOWS_PHONE_APP for Windows Phone 8.1 code

Secure storage using Xamarin Essentials

In my post Fingerprint and biometrics authentication in Xamarin Forms I looked at using biometrics (face id/touch id) to authenticate a user.

Using biometrics is pretty useful, but ultimately we’d usually want to use the biometrics along with some way of storing a token, password or whatever. In other words the usual pattern would be something like this

  • Request the user login details and then ask if the user wishes to use biometrics to log into your application (as this post is about using biometrics etc. let’s assume the user does indeed want to use biometrics)
  • Store the token or other details for the successful login within secure storage
  • When the user next try to log into your application, offer an option to use the password to login but by default give an option to login via biometrics
  • Assuming the user selects biometrics, then use the previously show code for biometric authorisations
  • Upon success of the biometrics authorisation, get the token/password etc. from the secure storage and use that to connect to your application/service

So how do we use secure storage within Xamarin forms. The Xamarin Essential nuget package give us SetAsync, for example

await Xamarin.Essentials.SecureStorage.SetAsync(key, token);

and to read back from the storage we use GetAsync, for example

var token = Xamarin.Essentials.SecureStorage.GetAsync(key);

Change the colour of the status bar on iOS (in Xamarin Forms)

As per my previous post Change the colour of the status bar on Android (in Xamarin Forms) we might wish to change the status bar on iOS.

Open Info.plist in a code editor and add the following (if it does not already exist)

<key>UIStatusBarStyle</key>
<string>UIStatusBarStyleLightContent</string>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>

Basically we’re disabling the status bar from taking it’s appearance from the preferred style of the current view controller – see UIViewControllerBasedStatusBarAppearance.

Fingerprint and biometrics authentication in Xamarin Forms

This is something I’ve wanted to try for a while and there’s a NuGet package that will allow us to enable and use biometric authentication with very little effort – much of this post will end up covering the github README at Biometric / Fingerprint plugin for Xamarin. So I strongly recommend checking that out.

Create a sample application

Let’s create a new Xamarin Forms application to test this out. So follow these steps to get up and running…

  • In Visual Studio create a new project – Mobile App (Xamarin.Forms)
  • At the solution level, right mouse click in Visual Studio 2019 and select Manage NuGet Packages for Solution
  • Browse for Plugin.Fingerprint by Sven-Michael Stübe
  • Click on the package then check each of your projects, shared and platform specific. We need to add the plugin to all projects, then click Install
  • In the Android MainActivity.cs file, OnCreate method after Xamarin.Essentials.Platform.Init(this, savedInstanceState); add
    CrossFingerprint.SetCurrentActivityResolver(
       () => Xamarin.Essentials.Platform.CurrentActivity);
    
  • In the Android Manifest add Required Permissions USE_FINGERPRINT
  • In the iOS project, open the Info.plist in code (F7) and add the following
    <key>NSFaceIDUsageDescription</key>
    <string>Use your face to authenticate</string>
    

    Ofcourse the string can be whatever you want.

Now we’ve got the project and configuration set up you’ll want some popup, page or just a button on your MainPage.xaml to initiate the Fingerprint/Biometrics login. For now let’s just add a Button to the MainPage.xaml and, for brevity, just add a Clicked handler, so for example

<Button Clicked="Button_OnClicked" Text="Authenticate with Biometrics" />

and here’s the code within the code behind for Button_OnClicked

private async void Button_OnClicked(object sender, EventArgs e)
{
   if (await CrossFingerprint.Current.IsAvailableAsync(true))
   {
      var result = await CrossFingerprint.Current.AuthenticateAsync(
         new AuthenticationRequestConfiguration("Login", "Access your account"));
      if (result.Authenticated)
      {
         await DisplayAlert("Success", "Authenticated", "OK");
      }
      else
      {
         await DisplayAlert("Failure", "Not Authenticated", "OK");
      }
   }
   else
   {
      await DisplayAlert("Failure", "Biometrics not available", "OK");
   }
}

We begin by checking if biometrics are available, passing in true will allow fallback to pin authentication. Assuming biometrics are available we then display the authentication mechanism using AuthenticateAsync passing in configuration that, in this case, will display some text on the fingerprint popup. If we’re authenticate then we display an alert to show success, in this example, but ofcourse you’ll handle success and failure as needed by your application.

Testing in the Android emulator

To test this application in the Android emulator

  • Goto the Settings within the Android OS and select Security
  • Under Device Security select Screen lock and add a pin
  • Under Device Security select Fingerprint and add a fingerprint, now to actually add a fingerprint we’ll click the … on the emulator and select Fingerprint, then click the Touch the Sensor button twice – you’re see the Fingerprint dialog go 50% of the way then 100% on the second click, finally click Done

Once we’re set up the security on the emulator and supplied one or more fingerprints run up your Xamarin Forms application and click the button you added. You’ll be presented with the AuthenticationRequestConfiguration you added, again using the … button on the emulator (if you closed the Extended controls dialog), select Fingerprint and click Touch the Sensore – this basically emulates a fingerprint touching the sensor.

To test for success, ensure the Fingerprint selected is one you added, i.e. by default Finger 1, to test for failure simply select one of the other, non-configured fingers and click Touch the Sensor

Testing in the iOS simulator

The setup for testing using the iOS simulator is a little simpler than Android…

  • Open the simulator and (in the latest XCode I’m using 13 but basically 12.x and above) select Features | Touch ID or Face ID (whichever is available on your simulator) and check the Enrolled option to show a tick (untick to remove the feature).

Now when you click your authentication button in your Xamarin forms application you may be presented with the dialog to allow the permission to be used, once you’ve accepted this you won’t see it again. Next you’ll see a small grey square which will denote your Face ID authentication (or for Touch ID you’ll get the fingerprint dialog), from the simulator’s Features and Face ID submenu, select Matching Face to simulate a successful authentication or Non-matching Face for a failure. For Touch ID simulators select Matching Touch for successful authentication or Non-matching Touch for a failure.

Code

Code for this post is available on GitHub.

References

Biometric / Fingerprint plugin for Xamarin
Enrolling a Fingerprint

Change the colour of the status bar on Android (in Xamarin Forms)

In your Android project, values folder styles.xml file you’ll find something like

<style name="MainTheme" parent="MainTheme.Base">
   <!-- -->
</style>

and/or

<style name="MainTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
   <!-- -->
</style>

Use the following element and attribute in the MainTheme.Base if that exists or the MainTheme (it will depend on the template you used at to whether one or both of these exist)

<!-- Top status bar area on Android -->
<item name="android:statusBarColor">#FF0C1436</item> 

You may wish to also change the colour of the bar background at the top of the NavigationPage (if you’re using the NavigationPage such as with Prism) by adding the following to the App.xaml

<Application.Resources>
  <ResourceDictionary>
    <Style TargetType="NavigationPage">
      <Setter Property="BarBackgroundColor" Value="Color.Red"/>
      <Setter Property="BarTextColor" Value="Color.White"/>
    </Style>
  </ResourceDictionary>
</Application.Resources>

in non-Prism you can change the Primary colour, for example again in App.xaml

<Application.Resources>
  <ResourceDictionary>
    <Color x:Key="Primary">#FF3399FF</Color>
  </ResourceDictionary>
</Application.Resources>

Custom Fonts in Xamarin Forms v4.5.0.530

In my previous post Custom Fonts in Xamarin Forms the section title Preview Feature is now working.

We’re use the Lobster-Regular.ttf file mentioned in the aforementioned post.

  • Add a Resources/Fonts folder to your shared project
  • Add your .otf or .ttf file to this Fonts folder
  • Set the Build Action to Embedded resource
  • In you AssemblyInfo.cs file add
    [assembly: ExportFont("Lobster-Regular.ttf")]
    
  • Now in your XAML you simply use
    <Label Text="Hello Xamarin.Forms"
       FontFamily="Lobster-Regular" />
    

That’s all there is to it.

You may still want to use the previous method for custom fonts if applying either different fonts to different devices, otherwise, this is such a simple and natural way to handle this task.

Text to Speech on mobile with Xamarin

Previously I looked at Speech synthesis in Windows with C# but what about speech synthesis on mobile.

Xamarin.Essentials has this covered with the TextToSpeechTextToSpeech class and is included by default when creating a Xamarin Forms mobile application.

It’s really simple to add text to speech capabilities, we simply write code such as

await TextToSpeech.SpeakAsync("Hello World");

As you can see by the use of the await keyword (and the standard Async suffix), the SpeakAsync method returns a task. It also accepts a cancellation token if you need to cancel mid utterance. There’s also an overload which accepts SpeechOptions which allows us to set the volume, pitch and locale.

The second TextToSpeech method is GetLocalesAsync which allows is to get a list of supported locales from the device that can then be used within the SpeakAsync method’s SpeechOptions.

await TextToSpeech.GetLocalesAsync();

Note: It’s fun listening to the attempts at different accents depending upon the locale.

Adding a Tizen project to Xamarin Forms

The great thing about creating a Xamarin Forms project is that you can create projects for Android, iOS and UWP at the same time, but there’s no options for Tizen.

Assuming we’re installed the Tizen Visual Studio templates, then it’s easy to add Tizen to an existing Xamarin Forms project and have it use the shared code project.

Assuming you’ve already created a Mobile App (Xamarin.Forms) application (mine’s called MyProject) and selected Android, iOS and UWP, now…

  • From File | New | Project select the Tizen XAML App (Xamarin.Forms) project, name the project along the lines of MyProject.Tizen
  • After you click Create you’ll be presented with the Tizen Project Wizard
  • Select Common (if not already selected) and leave Mobile, TV etc. options unchecked
  • Select the option Select Project in Solution and choose the shared project name, i.e. ours is MyProject
  • Click OK

Now you’ll see the Tizen project and it’s already set up to use your project’s shared code. So we can write our XAML for all four platforms. Obviously if we’re aiming to deploy to a watch (for example) we’ll need to optimise the XAML for this type of device. We use OnIdiom, for example

FontSize="{OnIdiom Watch=Small, Phone=Large}

and we’re done.