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 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); } }); }
public async Task <int> QueryLastRegistratetHeartRate() { var heartRateType = HKQuantityType.GetQuantityType(HKQuantityTypeIdentifierKey.HeartRate); int lastRegistratedHeartRate = 0; var timeSortDescriptor = new NSSortDescriptor(HKSample.SortIdentifierEndDate, false); var query = new HKSampleQuery(heartRateType, new NSPredicate(IntPtr.Zero), 1, new NSSortDescriptor[] { timeSortDescriptor }, (HKSampleQuery resultQuery, HKSample[] results, NSError error) => { string resultString = string.Empty; string source = string.Empty; HKQuantity quantity = null; if (results.Length != 0) { resultString = results [results.Length - 1].ToString(); lastRegistratedHeartRate = ParseHeartRateResultToBeatsPrMinute(resultString); var quantiyResult = (HKQuantitySample)results [results.Length - 1]; source = quantiyResult.Source.Name; HealthKitDataContext.ActiveHealthKitData.HeartRateReadings.LastRegisteredHeartRate = lastRegistratedHeartRate; HealthKitDataContext.ActiveHealthKitData.HeartRateReadings.Source = source; Console.WriteLine(string.Format("lastRegistratedHeartRate: {0}", lastRegistratedHeartRate)); } }); await Task.Factory.StartNew(() => HealthKitStore.ExecuteQuery(query)); return(lastRegistratedHeartRate); }
void UpdateUsersHeight() { var heightType = HKQuantityType.GetQuantityType(HKQuantityTypeIdentifierKey.Height); FetchMostRecentData(heightType, (mostRecentQuantity, error) => { if (error != null) { Console.WriteLine("An error occured fetching the user's height information. " + "In your app, try to handle this gracefully. The error was: {0}.", error.LocalizedDescription); return; } double usersHeight = 0.0; if (mostRecentQuantity != null) { var heightUnit = HKUnit.Inch; usersHeight = mostRecentQuantity.GetDoubleValue(heightUnit); } InvokeOnMainThread(delegate { heightValueLabel.Text = numberFormatter.StringFromNumber(new NSNumber(usersHeight)); }); }); }
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); } }); } }
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(); }); }
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(); }); }
public async Task <double> QueryTotalHeight() { var heightType = HKQuantityType.GetQuantityType(HKQuantityTypeIdentifierKey.Height); double usersHeight = 0.0; var timeSortDescriptor = new NSSortDescriptor(HKSample.SortIdentifierEndDate, false); var query = new HKSampleQuery(heightType, new NSPredicate(IntPtr.Zero), 1, new NSSortDescriptor[] { timeSortDescriptor }, (HKSampleQuery resultQuery, HKSample[] results, NSError error) => { HKQuantity quantity = null; if (results.Length != 0) { var quantitySample = (HKQuantitySample)results [results.Length - 1]; quantity = quantitySample.Quantity; usersHeight = quantity.GetDoubleValue(HKUnit.Meter); HealthKitDataContext.ActiveHealthKitData.Height = usersHeight; Console.WriteLine(string.Format("height of Fetched: {0}", usersHeight)); } }); await Task.Factory.StartNew(() => HealthKitStore.ExecuteQuery(query)); return(usersHeight); }
public async Task <int> QueryLastRegistratedSteps() { var stepType = HKQuantityType.GetQuantityType(HKQuantityTypeIdentifierKey.StepCount); int lastRegistratedSteps = 0; var timeSortDescriptor = new NSSortDescriptor(HKSample.SortIdentifierEndDate, false); var query = new HKSampleQuery(stepType, new NSPredicate(IntPtr.Zero), 1, new NSSortDescriptor[] { timeSortDescriptor }, (HKSampleQuery resultQuery, HKSample[] results, NSError error) => { HKQuantity quantity = null; if (results.Length != 0) { var quantitySample = (HKQuantitySample)results [results.Length - 1]; quantity = quantitySample.Quantity; var source = quantitySample.Source.Name; lastRegistratedSteps = (int)quantity.GetDoubleValue(HKUnit.Count); HealthKitDataContext.ActiveHealthKitData.DistanceReadings.TotalStepsOfLastRecording = lastRegistratedSteps; HealthKitDataContext.ActiveHealthKitData.DistanceReadings.Source = source; } }); m_healthKitStore.ExecuteQuery(query); return(lastRegistratedSteps); }
public async Task <double> QueryLastRegistratedWalkingDistance() { var distanceType = HKQuantityType.GetQuantityType(HKQuantityTypeIdentifierKey.DistanceWalkingRunning); double lastRegistratedWalkingDistance = 0.0; var timeSortDescriptor = new NSSortDescriptor(HKSample.SortIdentifierEndDate, false); var query = new HKSampleQuery(distanceType, new NSPredicate(IntPtr.Zero), 1, new NSSortDescriptor[] { timeSortDescriptor }, (HKSampleQuery resultQuery, HKSample[] results, NSError error) => { HKQuantity quantity = null; string resultString = string.Empty; if (results.Length != 0) { var quantitySample = (HKQuantitySample)results [results.Length - 1]; quantity = quantitySample.Quantity; lastRegistratedWalkingDistance = quantity.GetDoubleValue(HKUnit.Meter); HealthKitDataContext.ActiveHealthKitData.DistanceReadings.TotalDistanceOfLastRecording = lastRegistratedWalkingDistance; Console.WriteLine(string.Format("value of QueryLastRegistratedWalkingDistance: {0}", lastRegistratedWalkingDistance)); } }); m_healthKitStore.ExecuteQuery(query); return(lastRegistratedWalkingDistance); }
//Attempts to store in the Health Kit database a quantity, which must be of a type compatible with beats-per-minute public void StoreHeartRate(HKQuantity quantity) { var bpm = HKUnit.Count.UnitDividedBy(HKUnit.Minute); //Confirm that the value passed in is of a valid type (can be converted to beats-per-minute) if (!quantity.IsCompatible(bpm)) { InvokeOnMainThread(() => ErrorMessageChanged(this, new GenericEventArgs <string> ("Units must be compatible with BPM"))); } var heartRateId = HKQuantityTypeIdentifierKey.HeartRate; var heartRateQuantityType = HKQuantityType.GetQuantityType(heartRateId); var heartRateSample = HKQuantitySample.FromType(heartRateQuantityType, quantity, new NSDate(), new NSDate(), new HKMetadata()); using (var healthKitStore = new HKHealthStore()) { healthKitStore.SaveObject(heartRateSample, (success, error) => { InvokeOnMainThread(() => { if (success) { HeartRateStored(this, new GenericEventArgs <Double> (quantity.GetDoubleValue(bpm))); } else { ErrorMessageChanged(this, new GenericEventArgs <string> ("Save failed")); } if (error != null) { //If there's some kind of error, disable Enabled = false; ErrorMessageChanged(this, new GenericEventArgs <string> (error.ToString())); } }); }); } }
public override async Task <bool> IsSetup() { // Lets try and read the date of birth return(HealthStore.GetAuthorizationStatus(HKQuantityType.GetQuantityType(HKQuantityTypeIdentifierKey.Height)) == HKAuthorizationStatus.SharingAuthorized); }