public void FetchSteps(Action <double> completionHandler) { var calendar = NSCalendar.CurrentCalendar; var startDate = DateTime.Today; var endDate = DateTime.Now; var stepsQuantityType = HKQuantityType.Create(HKQuantityTypeIdentifier.StepCount); var predicate = HKQuery.GetPredicateForSamples((NSDate)startDate, (NSDate)endDate, HKQueryOptions.StrictStartDate); var query = new HKStatisticsQuery(stepsQuantityType, predicate, HKStatisticsOptions.CumulativeSum, (HKStatisticsQuery resultQuery, HKStatistics results, NSError error) => { if (error != null && completionHandler != null) { completionHandler(0.0f); } var totalSteps = results.SumQuantity(); if (totalSteps == null) { totalSteps = HKQuantity.FromQuantity(HKUnit.Count, 0.0); } completionHandler(totalSteps.GetDoubleValue(HKUnit.Count)); }); HealthStore.ExecuteQuery(query); }
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); } }); } }
//Converts its argument into a strongly-typed quantity representing the value in beats-per-minute public HKQuantity HeartRateInBeatsPerMinute(ushort beatsPerMinute) { var heartRateUnitType = HKUnit.Count.UnitDividedBy(HKUnit.Minute); var quantity = HKQuantity.FromQuantity(heartRateUnitType, beatsPerMinute); return(quantity); }
private static HKQuantitySample CreateBloodGlucoseHKSample( int measureId, DateTime date, int version, int level ) { var metadata = new NSDictionary( MetadataKey.DiabettoOrigin, NSObject.FromObject(true), HKMetadataKey.TimeZone, NSObject.FromObject("UTC"), HKMetadataKey.SyncVersion, NSObject.FromObject(version), HKMetadataKey.WasUserEntered, NSObject.FromObject(true), HKMetadataKey.ExternalUuid, NSObject.FromObject(MetadataKey.GetExternalUUID(measureId)), HKMetadataKey.SyncIdentifier, NSObject.FromObject(MetadataKey.GetBloodGlucoseIdentifier(measureId))); return(HKQuantitySample.FromType( HKQuantityType.Create(HKQuantityTypeIdentifier.BloodGlucose), HKQuantity.FromQuantity( HKUnit .CreateMoleUnit(HKMetricPrefix.Milli, HKUnit.MolarMassBloodGlucose) .UnitDividedBy(HKUnit.Liter), level / 10.0), (NSDate)date, (NSDate)date, metadata)); }
public void AddFoodItem(FoodItem item) { var quantityType = HKQuantityType.GetQuantityType(HKQuantityTypeIdentifierKey.DietaryEnergyConsumed); var quantity = HKQuantity.FromQuantity(HKUnit.Joule, item.Joules); var now = NSDate.Now; var metadata = new NSDictionary(HKMetadataKey.FoodType, item.Name); var caloriesSample = HKQuantitySample.FromType(quantityType, quantity, now, now, metadata); HealthStore.SaveObject(caloriesSample, (success, error) => { if (success) { FoodItems.Insert(item, 0); var indexPathForInsertedFoodItem = NSIndexPath.FromRowSection(0, 0); InvokeOnMainThread(() => { TableView.InsertRows(new NSIndexPath[] { indexPathForInsertedFoodItem }, UITableViewRowAnimation.Automatic); }); } else { Console.WriteLine("An error occured saving the food {0}. In your app, try to handle this gracefully. " + "The error was: {1}.", item.Name, error); } }); }
private static HKQuantitySample CreateInsulinHKSample( int measureId, DateTime date, int version, InsulinType type, int value ) { var metadata = new NSDictionary( MetadataKey.DiabettoOrigin, NSObject.FromObject(true), HKMetadataKey.InsulinDeliveryReason, NSObject.FromObject( type == InsulinType.Basal ? HKInsulinDeliveryReason.Basal : HKInsulinDeliveryReason.Bolus), HKMetadataKey.TimeZone, NSObject.FromObject("UTC"), HKMetadataKey.ExternalUuid, NSObject.FromObject(MetadataKey.GetExternalUUID(measureId)), HKMetadataKey.WasUserEntered, NSObject.FromObject(true), HKMetadataKey.SyncVersion, NSObject.FromObject(version), HKMetadataKey.SyncIdentifier, NSObject.FromObject(MetadataKey.GetInsulinIdentifier(measureId, type))); return(HKQuantitySample.FromType( HKQuantityType.Create(HKQuantityTypeIdentifier.InsulinDelivery), HKQuantity.FromQuantity(HKUnit.InternationalUnit, value), (NSDate)date, (NSDate)date, metadata)); }
public override async Task <bool> WriteAsync(HealthDataType healthDataType, double value, DateTime start, DateTime?end = null) { if (end == null) { end = start; } var healthKit = healthDataType.ToHealthKit(); if (healthKit.HKType == HKTypes.Category) { var type = HKCategoryType.Create(healthDataType.ToHealthKit().CategoryTypeIdentifier); var sample = HKCategorySample.FromType(type, (nint)value, (NSDate)start, (NSDate)end); var(success, error) = await _healthStore.SaveObjectAsync(sample).ConfigureAwait(false); return(success); } else if (healthKit.HKType == HKTypes.Quantity) { var type = HKQuantityType.Create(healthDataType.ToHealthKit().QuantityTypeIdentifier); var quantity = HKQuantity.FromQuantity(healthDataType.ToHealthKit().Unit, value); var sample = HKQuantitySample.FromType(type, quantity, (NSDate)start, (NSDate)end); var(success, error) = await _healthStore.SaveObjectAsync(sample).ConfigureAwait(false); return(success); } else { throw new NotSupportedException(); } }
partial void ToggleWorkout() { if (IsWorkoutRunning && CurrentWorkoutSession != null) { HealthStore.EndWorkoutSession(CurrentWorkoutSession); IsWorkoutRunning = false; } else { // Begin workout. IsWorkoutRunning = true; // Clear the local Active Energy Burned quantity when beginning a workout session. CurrentActiveEnergyQuantity = HKQuantity.FromQuantity(HKUnit.Kilocalorie, 0.0); CurrentQuery = null; ActiveEnergySamples = new List <HKSample> (); // An indoor walk workout session. There are other activity and location types available to you. // Create a workout configuration var configuration = new HKWorkoutConfiguration { ActivityType = HKWorkoutActivityType.Walking, LocationType = HKWorkoutSessionLocationType.Indoor }; NSError error = null; CurrentWorkoutSession = new HKWorkoutSession(configuration, out error) { Delegate = this }; HealthStore.StartWorkoutSession(CurrentWorkoutSession); } }
void FetchMostRecentData(Action <double, NSError> completionHandler) { var calendar = NSCalendar.CurrentCalendar; var startDate = DateTime.Now.Date; var endDate = startDate.AddDays(1); var sampleType = HKQuantityType.GetQuantityType(HKQuantityTypeIdentifierKey.DietaryEnergyConsumed); var predicate = HKQuery.GetPredicateForSamples((NSDate)startDate, (NSDate)endDate, HKQueryOptions.StrictStartDate); var query = new HKStatisticsQuery(sampleType, predicate, HKStatisticsOptions.CumulativeSum, (HKStatisticsQuery resultQuery, HKStatistics results, NSError error) => { if (error != null && completionHandler != null) { completionHandler(0.0f, error); } var totalCalories = results.SumQuantity(); if (totalCalories == null) { totalCalories = HKQuantity.FromQuantity(HKUnit.Joule, 0.0); } if (completionHandler != null) { completionHandler(totalCalories.GetDoubleValue(HKUnit.Joule), error); } }); HealthStore.ExecuteQuery(query); }
public void FetchMetersWalked(Action <double> completionHandler) { var calendar = NSCalendar.CurrentCalendar; var startDate = DateTime.Today; var endDate = DateTime.Now; var stepsQuantityType = HKQuantityType.Create(HKQuantityTypeIdentifier.DistanceWalkingRunning); var predicate = HKQuery.GetPredicateForSamples((NSDate)startDate, (NSDate)endDate, HKQueryOptions.StrictStartDate); var query = new HKStatisticsQuery(stepsQuantityType, predicate, HKStatisticsOptions.CumulativeSum, (HKStatisticsQuery resultQuery, HKStatistics results, NSError error) => { if (error != null && completionHandler != null) { completionHandler(0); } var distance = results.SumQuantity(); if (distance == null) { distance = HKQuantity.FromQuantity(HKUnit.Meter, 0); } completionHandler(distance.GetDoubleValue(HKUnit.Meter)); }); HealthStore.ExecuteQuery(query); }
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()}."); } }); } }); }
private HKQuantity getCaloriesFromData(ExerciseData data) { //0,029 x(peso corporal en kg) x 2,2 x Total de minutos practicados = cantidad de calorĂas aproximadas quemadas double userWeight = 88.0; double weigthEdit = 0.029; double timeEdit = 2.2; var kilocalories = weigthEdit * userWeight; kilocalories = kilocalories * (timeEdit * data.Time.TotalMinutes); kilocalories = Math.Round(kilocalories, 2); return(HKQuantity.FromQuantity(HKUnit.Kilocalorie, kilocalories)); }
void SaveHeightIntoHealthStore(double value) { var heightQuantity = HKQuantity.FromQuantity(HKUnit.Inch, value); var heightType = HKQuantityType.GetQuantityType(HKQuantityTypeIdentifierKey.Height); var heightSample = HKQuantitySample.FromType(heightType, heightQuantity, NSDate.Now, NSDate.Now, new NSDictionary()); HealthStore.SaveObject(heightSample, (success, error) => { if (!success) { Console.WriteLine("An error occured saving the height sample {0}. " + "In your app, try to handle this gracefully. The error was: {1}.", heightSample, error); return; } UpdateUsersHeight(); }); }
private void SaveWeight(HKHealthStore store) { var massKey = HKQuantityTypeIdentifierKey.BodyMass; var massQuantityType = HKObjectType.GetQuantityType(massKey); var currentMass = HKQuantity.FromQuantity(HKUnit.FromMassFormatterUnit(NSMassFormatterUnit.Kilogram), 77.0); var massSample = HKQuantitySample.FromType(massQuantityType, currentMass, new NSDate(), new NSDate(), new HKMetadata()); store.SaveObject(massSample, (success, error) => { Console.WriteLine("Write succeeded: " + success); if (error != null) { Console.WriteLine(error); } }); }
void SaveWeightIntoHealthStore(double value) { var weightQuantity = HKQuantity.FromQuantity(HKUnit.Pound, value); var weightType = HKQuantityType.GetQuantityType(HKQuantityTypeIdentifierKey.BodyMass); var weightSample = HKQuantitySample.FromType(weightType, weightQuantity, NSDate.Now, NSDate.Now, new NSDictionary()); HealthStore.SaveObject(weightSample, (success, error) => { if (!success) { Console.WriteLine("An error occured saving the weight sample {0}. " + "In your app, try to handle this gracefully. The error was: {1}.", weightSample, error.LocalizedDescription); return; } UpdateUsersWeight(); }); }
/* * 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); }
public Task <bool> SaveWeightIntoHealthStore(WeightData weight) { var weightQuantity = HKQuantity.FromQuantity(HKUnit.Gram, weight.Value * 1000); var weightType = HKQuantityType.Create(HKQuantityTypeIdentifier.BodyMass); var weightSample = HKQuantitySample.FromType(weightType, weightQuantity, DateUtil.DateTimeToNSDate(weight.Date), DateUtil.DateTimeToNSDate(weight.Date), new NSDictionary()); var completionSource = new TaskCompletionSource <bool>(); HealthStore.SaveObject(weightSample, (success, error) => { if (!success) { completionSource.SetResult(false); } else { completionSource.SetResult(true); } }); return(completionSource.Task); }
partial void OnToggleWorkout() { if (!IsWorkoutRunning && CurrentWorkoutSession == null) { // Begin workoutt IsWorkoutRunning = true; ToggleWorkoutButton.SetTitle("Rest little Baby");; // Clear the local Active Energy Burned quantity when beginning a workout session CurrentActiveEnergyQuantity = HKQuantity.FromQuantity(HKUnit.Kilocalorie, 0.0); CurrentHeartRate = HKQuantity.FromQuantity(HKUnit.FromString("count/min"), 0.0); CurrentQuery = null; HeartRateQuery = null; ActiveEnergySamples = new List <HKSample>(); HeartRateSamples = new List <HKSample>(); // An indoor walk workout session. There are other activity and location types available to you. // Create a workout configuratio var configuration = new HKWorkoutConfiguration { ActivityType = HKWorkoutActivityType.Walking, // Why not crawling? : LocationType = HKWorkoutSessionLocationType.Indoor }; NSError error = null; CurrentWorkoutSession = new HKWorkoutSession(configuration, out error) { Delegate = this }; HealthStore.StartWorkoutSession(CurrentWorkoutSession); } else { HealthStore.EndWorkoutSession(CurrentWorkoutSession); IsWorkoutRunning = false; ResetUI(); } }
public void AddStepCountEntry(StepCountEntry entry) { var date = new NSDate(); var quantityType = HKObjectType.GetQuantityType(HKQuantityTypeIdentifierKey.StepCount); var countUnit = HKUnit.Count; var quantity = HKQuantity.FromQuantity(countUnit, entry.Count); var sample = HKQuantitySample.FromType(quantityType, quantity, date, date); HealthStore.SaveObject(sample, new Action <bool, NSError>((success, error) => { if (!success || error != null) { //There may have been an add error for some reason. AlertManager.ShowError("Health Kit", "Unable to add step count sample: " + error); } else { //Refresh all app wide blood glucose UI fields. RefreshQuantityValue(HKQuantityTypeIdentifierKey.StepCount, quantityType); } })); }
/// <summary> /// This method handles all the HealthKit gymnastics to add a blood glucose entry to the HealthKit data. /// </summary> /// <param name="entry">Entry.</param> public void AddBloodGlucoseEntry(BloodGlucoseEntry entry) { var date = new NSDate(); var quantityType = HKObjectType.GetQuantityType(HKQuantityTypeIdentifierKey.BloodGlucose); var mgPerDL = HKUnit.FromString("mg/dL"); var quantity = HKQuantity.FromQuantity(mgPerDL, entry.BloodGlucoseValue); var sample = HKQuantitySample.FromType(quantityType, quantity, date, date); HealthStore.SaveObject(sample, new Action <bool, NSError>((success, error) => { if (!success || error != null) { //There may have been an add error for some reason. AlertManager.ShowError("Health Kit", "Unable to add glucose sample: " + error); } else { //Refresh all app wide blood glucose UI fields. RefreshQuantityValue(HKQuantityTypeIdentifierKey.BloodGlucose, quantityType); } })); }
private HKQuantity TotalDistanceQuantity() { return(HKQuantity.FromQuantity(HKUnit.Meter, this.TotalDistance)); }
private HKQuantity TotalBurningEnergyQuantity() { return(HKQuantity.FromQuantity(HKUnit.Kilocalorie, this.TotalEnergyBurned)); }
public void BeginWorkout(DateTime beginDate) { // Obtain the `HKObjectType` for active energy burned and the `HKUnit` for kilocalories. var activeEnergyType = HKQuantityType.Create(HKQuantityTypeIdentifier.ActiveEnergyBurned); if (activeEnergyType == null) { return; } var energyUnit = HKUnit.Kilocalorie; // Update properties. WorkoutBeginDate = beginDate; workoutButton.SetTitle("End Workout"); // Set up a predicate to obtain only samples from the local device starting from `beginDate`. var datePredicate = HKQuery.GetPredicateForSamples((NSDate)beginDate, null, HKQueryOptions.None); var devices = new NSSet <HKDevice> (new HKDevice[] { HKDevice.LocalDevice }); var devicePredicate = HKQuery.GetPredicateForObjectsFromDevices(devices); var predicate = NSCompoundPredicate.CreateAndPredicate(new NSPredicate[] { datePredicate, devicePredicate }); //Create a results handler to recreate the samples generated by a query of active energy samples so that they can be associated with this app in the move graph.It should be noted that if your app has different heuristics for active energy burned you can generate your own quantities rather than rely on those from the watch.The sum of your sample's quantity values should equal the energy burned value provided for the workout Action <List <HKSample> > sampleHandler; sampleHandler = (List <HKSample> samples) => { DispatchQueue.MainQueue.DispatchAsync(delegate { var accumulatedSamples = new List <HKQuantitySample> (); var initialActivityEnergy = CurrentActiveEnergyQuantity.GetDoubleValue(energyUnit); double accumulatedValue = initialActivityEnergy; foreach (HKQuantitySample sample in samples) { accumulatedValue = accumulatedValue + sample.Quantity.GetDoubleValue(energyUnit); var ourSample = HKQuantitySample.FromType(activeEnergyType, sample.Quantity, sample.StartDate, sample.EndDate); accumulatedSamples.Add(ourSample); } // Update the UI. CurrentActiveEnergyQuantity = HKQuantity.FromQuantity(energyUnit, accumulatedValue); activeEnergyBurnedLabel.SetText($"{accumulatedValue}"); // Update our samples. ActiveEnergySamples.AddRange(accumulatedSamples); }); }; // Create a query to report new Active Energy Burned samples to our app. var activeEnergyQuery = new HKAnchoredObjectQuery(activeEnergyType, predicate, null, HKSampleQuery.NoLimit, (query, addedObjects, deletedObjects, newAnchor, error) => { if (error == null) { // NOTE: `deletedObjects` are not considered in the handler as there is no way to delete samples from the watch during a workout ActiveEnergySamples = new List <HKSample>(addedObjects); sampleHandler(ActiveEnergySamples); } else { Console.WriteLine($"An error occured executing the query. In your app, try to handle this gracefully. The error was: {error}."); } }); // Assign the same handler to process future samples generated while the query is still active. activeEnergyQuery.UpdateHandler = (query, addedObjects, deletedObjects, newAnchor, error) => { if (error == null) { ActiveEnergySamples = new List <HKSample> (addedObjects); sampleHandler(ActiveEnergySamples); } else { Console.WriteLine($"An error occured executing the query. In your app, try to handle this gracefully. The error was: {error}."); } }; // Start Query CurrentQuery = activeEnergyQuery; HealthStore.ExecuteQuery(activeEnergyQuery); }