public void SaveWorkout(HKWorkoutSession workoutSession, NSDate startDate, NSDate endDate) { // Create and save a workout sample var configuration = workoutSession.WorkoutConfiguration; var metadata = new HKMetadata { IndoorWorkout = configuration.LocationType == HKWorkoutSessionLocationType.Indoor, }; var workout = HKWorkout.Create(configuration.ActivityType, startDate, endDate, this.workoutEvents.ToArray(), this.TotalBurningEnergyQuantity(), this.TotalDistanceQuantity(), metadata); this.healthStore.SaveObject(workout, (isSuccess, error) => { if (isSuccess) { this.AddSamples(workout, startDate, endDate); } }); }
void UpdateHealthKit(string s) { //Creating a heartbeat sample int result = 0; if (Int32.TryParse(s, out result)) { var heartRateId = HKQuantityTypeIdentifierKey.HeartRate; var heartRateType = HKObjectType.GetQuantityType(heartRateId); var heartRateQuantityType = HKQuantityType.GetQuantityType(heartRateId); //Beats per minute = "Count/Minute" as a unit var heartRateUnitType = HKUnit.Count.UnitDividedBy(HKUnit.Minute); var quantity = HKQuantity.FromQuantity(heartRateUnitType, result); //If we know where the sensor is... var metadata = new HKMetadata(); metadata.HeartRateSensorLocation = HKHeartRateSensorLocation.Chest; //Create the sample var heartRateSample = HKQuantitySample.FromType(heartRateQuantityType, quantity, new NSDate(), new NSDate(), metadata); //Attempt to store it... healthKitStore.SaveObject(heartRateSample, (success, error) => { //Error will be non-null if permissions not granted Console.WriteLine("Write succeeded: " + success); if (error != null) { Console.WriteLine(error); } }); } }
private void AddSamples(HKWorkout workout, NSDate startDate, NSDate endDate) { // Create energy and distance sample var totalEnergyBurnedSample = HKQuantitySample.FromType(HKQuantityType.Create(HKQuantityTypeIdentifier.ActiveEnergyBurned), this.TotalBurningEnergyQuantity(), startDate, endDate); var totalDistanceSample = HKQuantitySample.FromType(HKQuantityType.Create(HKQuantityTypeIdentifier.DistanceWalkingRunning), this.TotalDistanceQuantity(), startDate, endDate); // add samples to workout this.healthStore.AddSamples(new HKSample[] { totalEnergyBurnedSample, totalDistanceSample }, workout, (isSuccess, error) => { if (isSuccess) { DispatchQueue.MainQueue.DispatchAsync(() => { WKInterfaceController.ReloadRootPageControllers(new string[] { nameof(SummaryInterfaceController) }, new NSObject[] { workout }, WKPageOrientation.Vertical, 0); }); } else { Console.WriteLine($"Adding workout subsamples failed with error: ({error?.Description ?? "unknown"})"); } }); // finish the route with a syn identifier so we can easily update the route later var objects = new NSObject[] { new NSString(new NSUuid().AsString()), NSNumber.FromInt32(1) }; var keys = new NSString[] { HKMetadataKey.SyncIdentifier, HKMetadataKey.SyncVersion }; var dictionary = NSDictionary.FromObjectsAndKeys(objects, keys); var metadata = new HKMetadata(dictionary); this.workoutRouteBuilder?.FinishRoute(workout, metadata, (workoutRoute, error) => { if (workoutRoute == null) { Console.WriteLine($"Finishing route failed with error: ({error?.Description ?? "unknown"})"); } }); }
/* * public async Task<bool> SaveBmi(double value, DateTime start, DateTime? end) * { * return await WriteAsync(HealthDataType.iOS_BodyMassIndex, value, start, end); * } * * public async Task<bool> SaveMindfulSession(int value, DateTime start, DateTime? end) * { * return await WriteAsync(HealthDataType.MindfulSession, value, start, end); * } * * public async Task<bool> SaveHeight(double value, DateTime start, DateTime? end) * { * return await WriteAsync(HealthDataType.Height, value, start, end); * } * * public async Task<bool> SaveWeight(double value, DateTime start, DateTime? end) * { * return await WriteAsync(HealthDataType.Weight, value, start, end); * } * * public async Task<bool> SaveStep(int value, DateTime start, DateTime? end) * { * return await WriteAsync(HealthDataType.StepCount, value, start, end); * } * * public async Task<bool> SaveSleepAnalysis(HKCategoryValueSleepAnalysis value, DateTime start, DateTime end) * { * return await WriteAsync(HealthDataType.SleepAnalysis, (int)value, start, end); * } */ public override async Task <bool> WriteAsync(WorkoutDataType workoutDataType, double calories, DateTime start, DateTime?end = null, string name = null) { var totalEnergyBurned = HKQuantity.FromQuantity(HKUnit.CreateJouleUnit(HKMetricPrefix.Kilo), 20); var metadata = new HKMetadata(); if (name != null) { metadata.WorkoutBrandName = name; } var workout = HKWorkout.Create(Convert(workoutDataType), (NSDate)start, (NSDate)end, new HKWorkoutEvent[] { }, totalEnergyBurned, null, metadata); var(success, error) = await _healthStore.SaveObjectAsync(workout); return(success); }
private void UpdateWorkoutLocationsRoute(HKWorkout workout, HKWorkoutRoute route, List <CLLocation> newLocations) { // create a workout route builder var workoutRouteBuilder = new HKWorkoutRouteBuilder(this.healthStore, null); // insert updated route locations workoutRouteBuilder.InsertRouteData(newLocations.ToArray(), (success, error) => { if (success) { var syncIdentifier = route.Metadata?.SyncIdentifier; if (!string.IsNullOrEmpty(syncIdentifier)) { // new metadata with the same sync identifier and a higher version var objects = new NSObject[] { new NSString(syncIdentifier), NSNumber.FromInt32(2) }; var keys = new NSString[] { HKMetadataKey.SyncIdentifier, HKMetadataKey.SyncVersion }; var dictionary = NSDictionary.FromObjectsAndKeys(objects, keys); var metadata = new HKMetadata(dictionary); // finish the route with updated metadata workoutRouteBuilder.FinishRoute(workout, metadata, (workoutRoute, routeRrror) => { if (workoutRoute != null) { Console.WriteLine($"Workout route updated: ({route})"); } else { Console.WriteLine($"An error occurred while finishing the new route: ({error?.LocalizedDescription ?? "Unknown"})"); } }); } else { throw new ArgumentNullException(nameof(syncIdentifier), "Missing expected sync identifier on route"); } } else { Console.WriteLine($"An error occurred while inserting route data ({error?.LocalizedDescription ?? "Unknown"})"); } }); }
public Task <ExerciseData> AddExercise(ExerciseData data) { var completionSource = new TaskCompletionSource <ExerciseData>(); var metadata = new HKMetadata() { GroupFitness = true, IndoorWorkout = true, CoachedWorkout = true, }; if (data.Time.TotalMinutes == 0) { DateTime start = ((DateTime)data.DateInit).ToLocalTime(); DateTime end = ((DateTime)data.DateEnd).ToLocalTime(); data.Time = end.Subtract(start); } HKQuantity calories = getCaloriesFromData(data); HKWorkout workOut = HKWorkout.Create(HKWorkoutActivityType.TraditionalStrengthTraining, data.DateInit, data.DateEnd, null, calories, null, metadata); HealthStore.SaveObject(workOut, (succes, error) => { if (succes) { data.Kilocalories = calories.GetDoubleValue(HKUnit.Kilocalorie); completionSource.SetResult(data); } else { completionSource.SetResult(null); } }); return(completionSource.Task); }
void UpdateHealthKit(string s) { //Creating a heartbeat sample int result = 0; if (Int32.TryParse (s, out result)) { var heartRateId = HKQuantityTypeIdentifierKey.HeartRate; var heartRateType = HKObjectType.GetQuantityType (heartRateId); var heartRateQuantityType = HKQuantityType.GetQuantityType (heartRateId); //Beats per minute = "Count/Minute" as a unit var heartRateUnitType = HKUnit.Count.UnitDividedBy (HKUnit.Minute); var quantity = HKQuantity.FromQuantity (heartRateUnitType, result); //If we know where the sensor is... var metadata = new HKMetadata (); metadata.HeartRateSensorLocation = HKHeartRateSensorLocation.Chest; //Create the sample var heartRateSample = HKQuantitySample.FromType (heartRateQuantityType, quantity, new NSDate (), new NSDate (), metadata); //Attempt to store it... healthKitStore.SaveObject (heartRateSample, (success, error) => { //Error will be non-null if permissions not granted Console.WriteLine ("Write succeeded: " + success); if (error != null) { Console.WriteLine (error); } }); } }