Ejemplo n.º 1
0
        //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);
        }
Ejemplo n.º 2
0
        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);
                    }
                });
            }
        }
        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);
        }
Ejemplo n.º 4
0
        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);
        }
        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 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);
                }
            });
        }
        void FetchMostRecentData(HKQuantityType quantityType, Action <HKQuantity, NSError> completion)
        {
            var timeSortDescriptor = new NSSortDescriptor(HKSample.SortIdentifierEndDate, false);
            var query = new HKSampleQuery(quantityType, null, 1, new NSSortDescriptor[] { timeSortDescriptor },
                                          (HKSampleQuery resultQuery, HKSample[] results, NSError error) => {
                if (completion != null && error != null)
                {
                    completion(null, error);
                    return;
                }

                HKQuantity quantity = null;
                if (results.Length != 0)
                {
                    var quantitySample = (HKQuantitySample)results [results.Length - 1];
                    quantity           = quantitySample.Quantity;
                }

                if (completion != null)
                {
                    completion(quantity, error);
                }
            });

            HealthStore.ExecuteQuery(query);
        }
Ejemplo n.º 8
0
        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));
        }
		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);
			}
		}
Ejemplo n.º 10
0
        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));
        }
Ejemplo n.º 11
0
        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();
            }
        }
Ejemplo n.º 12
0
        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);
        }
        private void GetDataFromQuery(DateTime start, DateTime end, HKQuantityType quentityType, HKUnit unit, Action <IEnumerable <double> > act)
        {
            NSCalendar       calendar = NSCalendar.CurrentCalendar;
            NSDateComponents interval = new NSDateComponents {
                Day = 1
            };
            NSDate startDate  = start.ToNsDate();
            NSDate anchorDate = end.ToNsDate();

            HKStatisticsCollectionQuery query = new HKStatisticsCollectionQuery(
                quentityType,
                null,
                HKStatisticsOptions.CumulativeSum,
                anchorDate,
                interval
                )
            {
                InitialResultsHandler = (localQuery, result, error) =>
                {
                    if (error != null)
                    {
                        OnError?.Invoke(error.Description);
                        return;
                    }
                    int      daysCount = (end - start).Days + 1;
                    double[] st        = new double[daysCount];

                    result.EnumerateStatistics(startDate, anchorDate, (statistics, stop) =>
                    {
                        HKQuantity quantity = statistics?.SumQuantity();

                        int index = (statistics.StartDate.ToDateTime() - start).Days;

                        if (index < 0 || index > st.Length)
                        {
                            return;
                        }

                        double value = quantity?.GetDoubleValue(unit) ?? 0;

                        st[index] = value;
                    });

                    act(st.AsEnumerable());
                }
            };

            try
            {
                _healthStore.ExecuteQuery(query);
            }
            catch (Exception e)
            {
                OnError?.Invoke(e.Message);
            }
        }
Ejemplo n.º 15
0
        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()}.");
                        }
                    });
                }
            });
        }
Ejemplo n.º 16
0
        public static string Format(HKQuantity totalDistance = null, HKQuantity totalEnergyBurned = null)
        {
            var result = string.Empty;

            if (totalDistance != null)
            {
                result = Format(totalDistance: totalDistance.GetDoubleValue(HKUnit.Meter));
            }
            else if (totalEnergyBurned != null)
            {
                result = Format(totalEnergyBurned: totalEnergyBurned.GetDoubleValue(HKUnit.Kilocalorie));
            }

            return(result);
        }
Ejemplo n.º 17
0
        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));
        }
        public static bool TryGetClassification(HKQuantity value, out HKAppleWalkingSteadinessClassification?classification, out NSError?error)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }
            classification = null;

            error = null;
            if (HKAppleWalkingSteadinessClassificationForQuantity(value.GetHandle(), out var classificationOut, out var errorPtr))
            {
                classification = (HKAppleWalkingSteadinessClassification)(long)classificationOut;
                error          = Runtime.GetNSObject <NSError> (errorPtr, false);
                return(true);
            }
            return(false);
        }
        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();
            });
        }
Ejemplo n.º 20
0
        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 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();
            });
        }
Ejemplo n.º 22
0
        /*
         * 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);
        }
Ejemplo n.º 23
0
        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);
        }
Ejemplo n.º 24
0
        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);
        }
Ejemplo n.º 25
0
        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();
            }
        }
        /// <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);
                }
            }));
        }
        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);
                }
            }));
        }
Ejemplo n.º 28
0
        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);
        }
Ejemplo n.º 29
0
        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 heartRateQuantityType = HKQuantityType.Create(HKQuantityTypeIdentifier.HeartRate);
            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?.Invoke(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()));
                        }
                    });
                });
            }
        }
Ejemplo n.º 30
0
        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);
        }
Ejemplo n.º 31
0
        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 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);
		}