Permissions made easy with Xamarin.Essentials
Published in
2 min readDec 10, 2020
If you need to use features like geolocation, contacts, or the camera we have to ask permission from the user.
Implementing permission in Xamarin forms was not as straight forward as we had to use native components. To the rescue came Xamarin.Essentials 1.5. It makes it easy to implement permissions like geolocation, contacts, or the camera.
Let's look at an example.
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
x:Class="PermissionEssentiial.MainPage"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
<StackLayout
Padding="30"
Spacing="30"
VerticalOptions="CenterAndExpand"> <Label
FontAttributes="Bold"
FontSize="Large"
HorizontalTextAlignment="Center"
Text="Location permission needed"
TextColor="Black" /> <Button
Margin="10,0"
BackgroundColor="#EE7E4C"
Command="{Binding PermissionCommand}"
CornerRadius="20"
FontSize="20"
Text="Give permission"
TextColor="Black" />
</StackLayout>
</ContentPage>
In the ViewModel
public class MainPageViewModel
{
public ICommand PermissionCommand { get; set; }
public MainPageViewModel()
{
PermissionCommand = new
Command(async () => await RequestPermissionAsync());
}async Task RequestPermissionAsync()
{
var status = await Permissions.CheckStatusAsync<Permissions.LocationWhenInUse>();
if (status != PermissionStatus.Granted)
{
status = await Permissions.RequestAsync<Permissions.LocationWhenInUse>();
}
}
}
This is the output you get
Note: You need to add permissions in the manifest file of android and the Info.plist file of iOS.