Exemple #1
0
        private void LoadWorkouts(Action <List <HKWorkout> > completion)
        {
            var workoutType = HKObjectType.GetWorkoutType();
            var predicate   = HKQuery.GetPredicateForObjectsFromSource(HKSource.GetDefaultSource);
            var query       = new HKSampleQuery(workoutType, predicate, HKSampleQuery.NoLimit, null, (sender, results, error) =>
            {
                var isSuccess = results != null;
                if (isSuccess)
                {
                    var workouts = results.OfType <HKWorkout>().ToList();
                    isSuccess    = workouts.Any();
                    if (isSuccess)
                    {
                        completion(workouts);
                    }
                }

                if (!isSuccess)
                {
                    Console.WriteLine($"An error occurred: ({error?.LocalizedDescription ?? "Unknown"})");
                }
            });

            this.healthStore.ExecuteQuery(query);
        }
        public void Workout()
        {
            TestRuntime.AssertXcodeVersion(6, 0);

            using (var t = HKObjectType.GetWorkoutType()) {
                Assert.That(t.Handle, Is.Not.EqualTo(IntPtr.Zero), "Handle");
            }
        }
Exemple #3
0
        public static async Task <IEnumerable <Workout> > GetWorkouts(HKHealthStore store, DateInterval dates)
        {
            var workoutType = HKObjectType.GetWorkoutType();

            var workouts = await RunQuery(store, workoutType, dates, sample => WorkoutParser.ParseWorkout((HKWorkout)sample));

            return(workouts.Match(
                       Some: w => w,
                       None: Enumerable.Empty <Workout>()));
        }
Exemple #4
0
        public void Workout()
        {
            if (!TestRuntime.CheckSystemAndSDKVersion(8, 0))
            {
                Assert.Inconclusive("Requires iOS8+");
            }

            using (var t = HKObjectType.GetWorkoutType()) {
                Assert.That(t.Handle, Is.Not.EqualTo(IntPtr.Zero), "Handle");
            }
        }
        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()}.");
                        }
                    });
                }
            });
        }
Exemple #6
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 ?? "");
                }
            });
        }
Exemple #7
0
        public async Task <Option <Error> > RequestAuthorizeAppleHealth()
        {
            var typesToRead = new NSSet(
                HKQuantityType.Create(HKQuantityTypeIdentifier.HeartRate)
                , HKQuantityType.Create(HKQuantityTypeIdentifier.RestingHeartRate)
                , HKQuantityType.Create(HKQuantityTypeIdentifier.WalkingHeartRateAverage)
                , HKQuantityType.Create(HKQuantityTypeIdentifier.HeartRateVariabilitySdnn)
                , HKQuantityType.Create(HKQuantityTypeIdentifier.BasalEnergyBurned)
                , HKQuantityType.Create(HKQuantityTypeIdentifier.ActiveEnergyBurned)
                , HKQuantityType.Create(HKQuantityTypeIdentifier.BodyFatPercentage)
                , HKQuantityType.Create(HKQuantityTypeIdentifier.BodyMass)
                , HKQuantityType.Create(HKQuantityTypeIdentifier.AppleExerciseTime)
                , HKQuantityType.Create(HKQuantityTypeIdentifier.AppleStandTime)
                , HKQuantityType.Create(HKQuantityTypeIdentifier.StepCount)
                , HKObjectType.GetWorkoutType()
                , HKCategoryType.Create(HKCategoryTypeIdentifier.AppleStandHour)
                , HKCategoryType.Create(HKCategoryTypeIdentifier.SleepAnalysis)
                , HKCategoryType.Create(HKCategoryTypeIdentifier.LowHeartRateEvent)
                , HKCategoryType.Create(HKCategoryTypeIdentifier.HighHeartRateEvent)
                );

            var result = await new HKHealthStore().RequestAuthorizationToShareAsync(
                typesToShare: new NSSet(),
                typesToRead: typesToRead);

            return(result.Item1
                ? Option <Error> .None
                : Option <Error> .Some(CreateError(result.Item2)));

            Error CreateError(NSError error)
            {
                var exception = new Exception(error.ToString());

                return(Error.New((int)error.Code, error.LocalizedDescription, Option <Exception> .Some(exception)));
            }
        }
        public override void WillActivate()
        {
            // Only proceed if health data is available.
            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.ActiveEnergyBurned), HKObjectType.GetWorkoutType());
            var typesToRead  = new NSSet(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.");
                }
            });
        }
Exemple #9
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() }
            }));
        }
Exemple #10
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);
        }