.NET MAUI exposes device features through APIs shared by every platform: location, camera, files, connectivity, device information. Before using them, though, you need permissions.
Requesting a permission
public async Task<Location?> CurrentLocationAsync()
{
var status = await Permissions.CheckStatusAsync<Permissions.LocationWhenInUse>();
if (status != PermissionStatus.Granted)
status = await Permissions.RequestAsync<Permissions.LocationWhenInUse>();
if (status != PermissionStatus.Granted)
return null; // the user refused: the app must keep working
return await Geolocation.Default.GetLocationAsync(
new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(10)));
}
On Android and iOS, permissions must also be declared in the platform files (AndroidManifest.xml and Info.plist), with a clear explanation of why: the stores check it.
Picking a photo
var photo = await MediaPicker.Default.PickPhotoAsync();
if (photo is not null)
{
await using var stream = await photo.OpenReadAsync();
await _upload.SendAsync(stream, photo.FileName);
}
Connectivity
if (Connectivity.Current.NetworkAccess != NetworkAccess.Internet)
{
await Shell.Current.DisplayAlert("Offline", "Data will be sent as soon as you are back online.", "OK");
}
Good practices
- Ask for permissions only when needed, in a context where the user understands why.
- Always handle refusal: the app must not get stuck.
- For features not covered by the shared APIs, use platform-specific code in the
Platformsfolders or partial classes.
Comments (0)
No comments yet.