Exemplo n.º 1
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);
                    }
                });
            }
        }
        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);
        }
Exemplo n.º 3
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();
            }
        }
Exemplo n.º 4
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));
        }
        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 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));
                });
            });
        }
        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);
        }
Exemplo n.º 8
0
        public void EnumValues_22351()
        {
            TestRuntime.AssertXcodeVersion(6, 0);

            foreach (HKQuantityTypeIdentifier value in Enum.GetValues(typeof(HKQuantityTypeIdentifier)))
            {
                // we need to have version checks for anything added after iOS 8.0
                switch (value)
                {
                case HKQuantityTypeIdentifier.BasalBodyTemperature:
                case HKQuantityTypeIdentifier.DietaryWater:
                case HKQuantityTypeIdentifier.UVExposure:
                    if (!TestRuntime.CheckXcodeVersion(7, 0))
                    {
                        continue;
                    }
                    break;
                }

                try {
                    using (var ct = HKQuantityType.Create(value)) {
                        Assert.That(ct.Handle, Is.Not.EqualTo(IntPtr.Zero), value.ToString());
                    }
                }
                catch (Exception e) {
                    Assert.Fail("{0} could not be created: {1}", value, e);
                }
            }
        }
        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);
        }
Exemplo 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));
        }
Exemplo n.º 11
0
        public override void WillActivate()
        {
            base.WillActivate();
            ResetUI();
            if (!HKHealthStore.IsHealthDataAvailable)
            {
                return;
            }
            // We need to be able to write workouts, so they display as a standalone workout in the Activity app on iPhone.
            // We also need to be able to write Active Energy Burned to write samples to HealthKit to later associating with our app.

            var typesToShare = new NSSet(HKQuantityType.Create(HKQuantityTypeIdentifier.HeartRate), HKQuantityType.Create(HKQuantityTypeIdentifier.ActiveEnergyBurned), HKObjectType.GetWorkoutType());
            var typesToRead  = new NSSet(HKQuantityType.Create(HKQuantityTypeIdentifier.HeartRate), HKQuantityType.Create(HKQuantityTypeIdentifier.ActiveEnergyBurned));

            HealthStore.RequestAuthorizationToShare(typesToShare, typesToRead, (bool success, NSError error) =>
            {
                if (error != null && !success)
                {
                    Console.WriteLine("You didn't allow HealthKit to access these read/write data types. " +
                                      "In your app, try to handle this error gracefully when a user decides not to provide access. " +
                                      $"The error was: {error.LocalizedDescription}. If you're using a simulator, try it on a device.");
                }
            });
            _dangerousHeartRate.Where(v => v > 30.0).Subscribe(
                v => SessionManager.SharedManager.UpdateApplicationContext(
                    new Dictionary <string, object>()
            {
                { "HeartRate", v.ToString() }
            }));
        }
Exemplo n.º 12
0
        private async Task DeleteSamples(Measure measure)
        {
            if (_suppressed)
            {
                return;
            }

            var predicate = HKQuery.GetPredicateForMetadataKey(
                HKMetadataKey.ExternalUuid,
                new[] { NSObject.FromObject(MetadataKey.GetExternalUUID(measure.Id)) });

            var result = await _healthStore.DeleteObjectsAsync(
                HKQuantityType.Create(HKQuantityTypeIdentifier.BloodGlucose),
                predicate);

            if (!result.Item1)
            {
                _log.Warn($"Can't delete blood glucose data by reason: {result.Item2.LocalizedDescription}");
            }

            result = await _healthStore.DeleteObjectsAsync(
                HKQuantityType.Create(HKQuantityTypeIdentifier.InsulinDelivery),
                predicate);

            if (!result.Item1)
            {
                _log.Warn($"Can't delete insulin data by reason: {result.Item2.LocalizedDescription}");
            }
        }
Exemplo n.º 13
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);
        }
        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);
        }
        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);
            }
        }
Exemplo n.º 16
0
        private void ValidateAuthorization()
        {
            var typesToShare = new NSSet(HKQuantityType.Create(HKQuantityTypeIdentifier.HeartRate), HKQuantityType.Create(HKQuantityTypeIdentifier.ActiveEnergyBurned), HKObjectType.GetWorkoutType());
            var typesToRead  = new NSSet(HKQuantityType.Create(HKQuantityTypeIdentifier.HeartRate), HKQuantityType.Create(HKQuantityTypeIdentifier.ActiveEnergyBurned));

            _healthStore.RequestAuthorizationToShare(
                typesToShare,
                typesToRead,
                ReactToHealthCarePermissions);
        }
Exemplo n.º 17
0
        NSSet DataTypesToRead(HealthDataType[] dataTypes)
        {
            var types = new HKObjectType[dataTypes.Length];

            for (var i = 0; i < dataTypes.Length; i++)
            {
                types.SetValue(HKQuantityType.Create(dataTypes[i].ToHealthKit().TypeIdentifier), i);
            }
            return(NSSet.MakeNSObjectSet(types));
        }
Exemplo n.º 18
0
        private void ValidateAuthorization()
        {
            var bodyMassType = HKQuantityType.Create(HKQuantityTypeIdentifier.BodyMass);
            var typesToWrite = new NSSet(new[] { bodyMassType });
            var typesToRead  = new NSSet(new[] { bodyMassType });

            healthKitStore.RequestAuthorizationToShare(
                typesToWrite,
                typesToRead,
                ReactToHealthCarePermissions);
        }
        public void EnumValues_22351()
        {
            TestRuntime.AssertXcodeVersion(6, 0);

            foreach (HKQuantityTypeIdentifier value in Enum.GetValues(typeof(HKQuantityTypeIdentifier)))
            {
                // we need to have version checks for anything added after iOS 8.0
                switch (value)
                {
                case HKQuantityTypeIdentifier.BasalBodyTemperature:
                case HKQuantityTypeIdentifier.DietaryWater:
                case HKQuantityTypeIdentifier.UVExposure:
                    if (!TestRuntime.CheckXcodeVersion(7, 0))
                    {
                        continue;
                    }
                    break;

                case HKQuantityTypeIdentifier.AppleExerciseTime:
                    if (!TestRuntime.CheckXcodeVersion(7, 3))
                    {
                        continue;
                    }
                    break;

                case HKQuantityTypeIdentifier.DistanceWheelchair:
                case HKQuantityTypeIdentifier.PushCount:
                case HKQuantityTypeIdentifier.DistanceSwimming:
                case HKQuantityTypeIdentifier.SwimmingStrokeCount:
                    if (!TestRuntime.CheckXcodeVersion(8, 0))
                    {
                        continue;
                    }
                    break;

                case HKQuantityTypeIdentifier.WaistCircumference:
                case HKQuantityTypeIdentifier.VO2Max:
                    if (!TestRuntime.CheckXcodeVersion(9, 0))
                    {
                        continue;
                    }
                    break;
                }

                try {
                    using (var ct = HKQuantityType.Create(value)) {
                        Assert.That(ct.Handle, Is.Not.EqualTo(IntPtr.Zero), value.ToString());
                    }
                }
                catch (Exception e) {
                    Assert.Fail("{0} could not be created: {1}", value, e);
                }
            }
        }
Exemplo n.º 20
0
        public bool GetStatus()
        {
            var pList                = NSUserDefaults.StandardUserDefaults;
            var isEnabled            = pList.BoolForKey(_userDefaultsKey);
            var isBloodGlucoseStatus = _healthStore.GetAuthorizationStatus(HKQuantityType.Create(HKQuantityTypeIdentifier.BloodGlucose));
            var isInsulinStatus      = _healthStore.GetAuthorizationStatus(HKQuantityType.Create(HKQuantityTypeIdentifier.InsulinDelivery));

            var hasAccessToHealthKit = isBloodGlucoseStatus == HKAuthorizationStatus.SharingAuthorized ||
                                       isInsulinStatus == HKAuthorizationStatus.SharingAuthorized;

            return(isEnabled && hasAccessToHealthKit);
        }
Exemplo n.º 21
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()}.");
                        }
                    });
                }
            });
        }
Exemplo n.º 22
0
        private void StartQuery(HKQuantityTypeIdentifier quantityTypeIdentifier, NSDate startDate, HKAnchoredObjectUpdateHandler handler)
        {
            var datePredicate   = HKQuery.GetPredicateForSamples(startDate, null, HKQueryOptions.StrictStartDate);
            var devicePredicate = HKQuery.GetPredicateForObjectsFromDevices(new NSSet <HKDevice>(HKDevice.LocalDevice));
            var queryPredicate  = NSCompoundPredicate.CreateAndPredicate(new NSPredicate[] { datePredicate, devicePredicate });

            var quantityType = HKQuantityType.Create(quantityTypeIdentifier);
            var query        = new HKAnchoredObjectQuery(quantityType, queryPredicate, null, HKSampleQuery.NoLimit, handler);

            query.UpdateHandler = handler;
            this.healthStore.ExecuteQuery(query);

            this.activeDataQueries.Add(query);
        }
Exemplo n.º 23
0
        void ReactToHealthCarePermissions(bool success, NSError error)
        {
            var access = healthKitStore.GetAuthorizationStatus(HKQuantityType.Create(HKQuantityTypeIdentifier.BodyMass));

            if (access.HasFlag(HKAuthorizationStatus.SharingAuthorized))
            {
                BodyMassModel.Instance.Enabled = true;
            }
            else
            {
                BodyMassModel.Instance.Enabled = false;
            }
            string temp = error.Description;
        }
Exemplo n.º 24
0
        public bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
            var read = new NSSet(HKQuantityType.Create(HKQuantityTypeIdentifier.HeartRate));

            var healthstore = new HKHealthStore();

            healthstore.RequestAuthorizationToShare(new NSSet(), read, (f, error) => {
                if (error != null)
                {
                    Console.WriteLine(@"{0} error", error);
                }
            });


            return(true);
        }
Exemplo n.º 25
0
        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"})");
                }
            });
        }
        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();
            });
        }
        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();
            });
        }
Exemplo n.º 28
0
        private void RequestAccessToHealthKit()
        {
            var healthStore = new HKHealthStore();

            var types = new NSSet(HKObjectType.GetWorkoutType(),
                                  HKSeriesType.WorkoutRouteType,
                                  HKQuantityType.Create(HKQuantityTypeIdentifier.ActiveEnergyBurned),
                                  HKQuantityType.Create(HKQuantityTypeIdentifier.DistanceWalkingRunning));

            healthStore.RequestAuthorizationToShare(types, types, (isSuccess, error) =>
            {
                if (!isSuccess)
                {
                    Console.WriteLine(error?.LocalizedDescription ?? "");
                }
            });
        }
Exemplo n.º 29
0
        public bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
            // Override point for customization after application launch.
            // If not required for your application you can safely delete this method

            var read = new NSSet(HKQuantityType.Create(HKQuantityTypeIdentifier.HeartRate));

            var healthstore = new HKHealthStore();

            healthstore.RequestAuthorizationToShare(new NSSet(), read, (f, error) => {
                if (error != null)
                {
                    Console.WriteLine(@"{0} error", error);
                }
            });

            return(true);
        }
Exemplo n.º 30
0
        private void FetchMostRecentData(HKQuantityType quantityType, Action <List <HKSample>, NSError> completion, int days)
        {
            var      timeSortDescriptor = new NSSortDescriptor(HKSample.SortIdentifierEndDate, false);
            DateTime startDay           = DateTime.Now;
            DateTime endDay             = startDay.AddDays(-days).AddHours(-startDay.Hour).AddMinutes(-startDay.Minute).AddSeconds(-startDay.Second).AddMilliseconds(-startDay.Millisecond);
            var      predicate          = HKQuery.GetPredicateForSamples(DateUtil.DateTimeToNSDate(endDay), DateUtil.DateTimeToNSDate(startDay), HKQueryOptions.None);
            var      query = new HKSampleQuery(quantityType, predicate, 0, new NSSortDescriptor[] { timeSortDescriptor },
                                               (HKSampleQuery resultQuery, HKSample[] results, NSError error) =>
            {
                if (completion != null && error != null)
                {
                    completion(null, error);
                    return;
                }

                completion?.Invoke(results.ToList(), error);
            });

            HealthStore.ExecuteQuery(query);
        }
        //void UpdateUsersAge ()
        //{
        //    NSError error;
        //    NSDate dateOfBirth = HealthStore.GetDateOfBirth (out error);

        //    if (error != null) {
        //        Console.WriteLine ("An error occured fetching the user's age information. " +
        //        "In your app, try to handle this gracefully. The error was: {0}", error);
        //        return;
        //    }

        //    if (dateOfBirth == null)
        //        return;

        //    var now = NSDate.Now;

        //    NSDateComponents ageComponents = NSCalendar.CurrentCalendar.Components (NSCalendarUnit.Year, dateOfBirth, now,
        //                                         NSCalendarOptions.WrapCalendarComponents);

        //    nint usersAge = ageComponents.Year;

        //    ageHeightValueLabel.Text = string.Format ("{0} years", usersAge);
        //}

        //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 UpdateUsersWeight ()
        //{
        //    var weightType = HKQuantityType.GetQuantityType (HKQuantityTypeIdentifierKey.BodyMass);

        //    FetchMostRecentData (weightType, (mostRecentQuantity, error) => {
        //        if (error != null) {
        //            Console.WriteLine ("An error occured fetching the user's age information. " +
        //            "In your app, try to handle this gracefully. The error was: {0}", error.LocalizedDescription);
        //            return;
        //        }

        //        double usersWeight = 0.0;

        //        if (mostRecentQuantity != null) {
        //            var weightUnit = HKUnit.Pound;
        //            usersWeight = mostRecentQuantity.GetDoubleValue (weightUnit);
        //        }

        //        InvokeOnMainThread (delegate {
        //            weightValueLabel.Text = numberFormatter.StringFromNumber (new NSNumber (usersWeight));
        //        });
        //    }
        //    );
        //}

        //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);
        //}

        void FetchData(HKQuantityType quantityType, Action<HKSample[], NSError> completion)
        {
            var timeSortDescriptor = new NSSortDescriptor(HKSample.SortIdentifierEndDate, false);
            var query = new HKSampleQuery(quantityType, null, 100, null,
                            (HKSampleQuery resultQuery, HKSample[] results, NSError error) =>
                            {
                                if (completion != null && error != null)
                                {
                                    completion(null, error);
                                    return;
                                }

                                if (completion != null)
                                    completion(results, error);
                            });

            HealthStore.ExecuteQuery(query);
        }
		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);
		}