public void SaveWorkout ()
{
// Obtain the `HKObjectType` for active energy burned.
var activeEnergyType = HKQuantityType.Create (HKQuantityTypeIdentifier.ActiveEnergyBurned);
if (activeEnergyType == null) return;
var beginDate = WorkoutBeginDate;
var endDate = WorkoutEndDate;
var timeDifference = endDate.Subtract (beginDate);
double duration = timeDifference.TotalSeconds;
NSDictionary metadata = null;
var workout = HKWorkout.Create (HKWorkoutActivityType.Walking,
(NSDate)beginDate,
(NSDate)endDate,
duration,
CurrentActiveEnergyQuantity,
HKQuantity.FromQuantity (HKUnit.Mile, 0.0),
metadata);
var finalActiveEnergySamples = ActiveEnergySamples;
if (HealthStore.GetAuthorizationStatus(activeEnergyType) != HKAuthorizationStatus.SharingAuthorized ||
HealthStore.GetAuthorizationStatus(HKObjectType.GetWorkoutType()) != HKAuthorizationStatus.SharingAuthorized)
return;
HealthStore.SaveObject(workout, (success, error) => {
if (!success) {
Console.WriteLine ($"An error occured saving the workout. In your app, try to handle this gracefully. The error was: {error}.");
return;
}
if (finalActiveEnergySamples.Count > 0) {
HealthStore.AddSamples (finalActiveEnergySamples.ToArray (), workout, (addSuccess, addError) => {
// Handle any errors
if (addError != null)
Console.WriteLine ($"An error occurred adding the samples. In your app, try to handle this gracefully. The error was: {error.ToString()}.");
});
}
});
}