Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
lawrence_shaun_introducing_net_maui_build_and_deploy_crosspl.pdf
Скачиваний:
46
Добавлен:
26.06.2023
Размер:
5.15 Mб
Скачать

Chapter 11 Getting Specific

Now that you have added the ability to request the user’s permission to use the geolocation APIs on the device, you can proceed to using it.

Using the Geolocation API

.NET MAUI provides the ability to access each platform’s geolocation APIs in order to retrieve a longitude and latitude representing where in the world the device running the application is currently located. Full details of what the API provides can be found at https://learn.microsoft.com/ dotnet/maui/platform-integration/device/geolocation.

Registering the Geolocation Service

Open the MauiProgram.cs file and register the geolocation implementation so that you can use it via the dependency injection layer. You need to add the following line into the CreateMauiApp method:

builder.Services.AddSingleton(Geolocation.Default);

Using the Geolocation Service

This now means that you can add a dependency on the IGeolocation interface and wherever .NET MAUI provides you with an instance. Let’s use the IGeolocation implementation in your LocationService.cs file. There are a few modifications you need to make, so I will walk through each one.

Add a field for the IGeolocation implementation in the root of the class.

private readonly IGeolocation geolocation;

Assign the IGeolocation implementation in the constructor.

public LocationService(IGeolocation geolocation)

{

341

Chapter 11 Getting Specific

this.geolocation = geolocation;

}

Provide the method to return a Location object.

public async Task<Location> GetLocationAsync()

{

return await MainThread.InvokeOnMainThreadAsync(async () =>

{

var status = await CheckAndRequestLocationPermission();

if (status != PermissionStatus.Granted)

{

return null;

}

return await this.geolocation.GetLocationAsync();

});

}

This implementation first makes sure that you are running on the main thread, which is required for location-based access. Then it calls your permission handling method and, if the app has permission, it calls the IGeolocation implementation and returns the resulting Location object. Now you are ready to make use of the LocationService.

Registering theLocationService

Open the MauiProgram.cs file and register the LocationService implementation so that you can use it via the dependency injection layer. You need to add the following line into the CreateMauiApp method:

builder.Services.AddSingleton<ILocationService,

LocationService>();

342

Chapter 11 Getting Specific

Using theILocationService

Let’s use the ILocationService implementation in your WeatherWidgetViewModel.cs file. There are a few modifications you need to make, so I will walk through each one

Add a field for the ILocationService implementation in the root of the class.

private readonly ILocationService locationService;

Assign the ILocationService implementation in the constructor; changes are in bold.

public WeatherWidgetViewModel( IWeatherForecastService weatherForecastService, ILocationService locationService)

{

this.weatherForecastService = weatherForecastService; this.locationService = locationService;

LoadWeatherCommand = new Command(async () => await LoadWeatherForecast());

}

Modify your State enum to include a new value so that you can handle when something goes wrong with permission access. Add a PermissionError value, as can be seen below in bold.

public enum State

{

None = 0, Loading = 1, Loaded = 2, Error = 3,

PermissionError = 4

}

343

Chapter 11 Getting Specific

Modify your LoadWeatherForecast method to call your new ILocationService implementation in order to find out the device’s location and then use that to call the Open Weather API to find out the weather at the device’s location.

private async Task LoadWeatherForecast()

{

State = State.Loading;

try

{

var location = await this.locationService. GetLocationAsync();

if (location is null)

{

State = State.PermissionError; return;

}

var forecast = await weatherForecastService. GetForecast(location.Latitude, location.Longitude);

Temperature = forecast.Current.Temperature; Weather = forecast.Current.Weather.First().Main; IconUrl = forecast.Current.Weather.First().IconUrl;

State = State.Loaded;

}

catch (Exception ex)

{

State = State.Error;

}

}

344