Now that we have created an interface for our location service and updated the ViewModel, we will need to create the concrete platform-specific implementations. Create the location service implementations as follows:
- First, create a new folder in the TripLog.iOS project named Services.
- Next, create a new class file in the Services folder named LocationService that implements the ILocationService interface we created earlier in the chapter:
public class LocationService : ILocationService
{
CLLocationManager _manager;
TaskCompletionSource<CLLocation> _tcs;
public async Task<GeoCoords> GetGeoCoordinatesAsync()
{
_manager = new CLLocationManager();
_tcs = new TaskCompletionSource<CLLocation>();
if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
{
_manager.RequestWhenInUseAuthorization();
}
_manager.LocationsUpdated += (s, e) =>
{
_tcs.TrySetResult(e.Locations[0]);
};
_manager.StartUpdatingLocation();
var location = await _tcs.Task;
return new GeoCoords
{
Latitude = location.Coordinate.Latitude,
Longitude = location.Coordinate.Longitude
};
}
}
- Next, create a new folder in the TripLog.Droid project named Services.
- Finally, create a new class file in the Services folder named LocationService that implements the ILocationService interface for Android:
public class LocationService
: Java.Lang.Object, ILocationService, ILocationListener
{
TaskCompletionSource<Location> _tcs;
public async Task<GeoCoords> GetGeoCoordinatesAsync()
{
var manager = (LocationManager)Forms.Context
.GetSystemService(Context.LocationService);
_tcs = new TaskCompletionSource<Location>();
manager.RequestSingleUpdate("gps", this, null);
var location = await _tcs.Task;
return new GeoCoords
{
Latitude = location.Latitude,
Longitude = location.Longitude
};
}
public void OnLocationChanged(Location location)
{
_tcs.TrySetResult(location);
}
public void OnProviderDisabled(string provider)
{
}
public void OnProviderEnabled(string provider)
{
}
public void OnStatusChanged(string provider,
[GeneratedEnum] Availability status, Bundle extras)
{
}
}
These are extremely over-simplified location service implementations. Most real-world scenarios will require more logic, however, for the purposes of demonstrating platform-specific service dependency injection, this implementation will suffice.
Now that we have created a platform-dependent service, it is time to register it into an IoC container so that we can use it throughout the rest of the code. In the next section, we will use Ninject to create registrations between both our location service interface and the actual platform-specific implementations. We will also update the custom navigation service that we created in Chapter 3, Navigation, to use Ninject in place of the default Xamarin.Forms DependencyService.