Пример #1
0
        protected override Task <List <Datum> > PollAsync(CancellationToken cancellationToken)
        {
            List <Datum> data = new List <Datum>();

            NSError error;
            HKWheelchairUseObject wheelChair = HealthStore.GetWheelchairUse(out error);

            if (error == null)
            {
                if (wheelChair.WheelchairUse == HKWheelchairUse.NotSet)
                {
                    data.Add(new WheelChairUseDatum(DateTimeOffset.Now, WheelChairUse.NotSet));
                }
                else if (wheelChair.WheelchairUse == HKWheelchairUse.No)
                {
                    data.Add(new WheelChairUseDatum(DateTimeOffset.Now, WheelChairUse.No));
                }
                else if (wheelChair.WheelchairUse == HKWheelchairUse.Yes)
                {
                    data.Add(new WheelChairUseDatum(DateTimeOffset.Now, WheelChairUse.Yes));
                }
                else
                {
                    throw new Exception("User has not provided -- or has not allowed access to -- their wheel chair use status.");
                }
            }
            else
            {
                throw new Exception("Error reading wheel chair use status:  " + error.Description);
            }

            return(Task.FromResult(data));
        }
        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);
                }
            });
        }
Пример #3
0
        public void DidReceiveUserInfo(WCSession session, NSDictionary <NSString, NSObject> userInfo)
        {
            var writer = new BarcodeWriter <UIImage>
            {
                Format  = BarcodeFormat.QR_CODE,
                Options = new EncodingOptions
                {
                    Height = 200,
                    Width  = 200,
                    Margin = 0
                },
                Renderer = new BarcodeRenderer()
            };

            var qrCodeUrl = new NSObject();

            userInfo.TryGetValue(new NSString("qrCode"), out qrCodeUrl);

            var img = writer.Write(qrCodeUrl.ToString());

            myImage.SetImage(img);
            myImage.SetRelativeWidth(0.98f, 0);
            myImage.SetRelativeHeight(0.98f, 0);

            var asdf = WKExtension.SharedExtension.Delegate as ExtensionDelegate;

            HealthStore.EndWorkoutSession(asdf.WorkoutSession);
        }
Пример #4
0
        protected override IEnumerable <Datum> Poll(CancellationToken cancellationToken)
        {
            List <Datum> data = new List <Datum>();

            NSError error;
            HKBiologicalSexObject biologicalSex = HealthStore.GetBiologicalSex(out error);

            if (error == null)
            {
                if (biologicalSex.BiologicalSex == HKBiologicalSex.Female)
                {
                    data.Add(new BiologicalSexDatum(DateTimeOffset.Now, BiologicalSex.Female));
                }
                else if (biologicalSex.BiologicalSex == HKBiologicalSex.Male)
                {
                    data.Add(new BiologicalSexDatum(DateTimeOffset.Now, BiologicalSex.Male));
                }
                else if (biologicalSex.BiologicalSex == HKBiologicalSex.Other)
                {
                    data.Add(new BiologicalSexDatum(DateTimeOffset.Now, BiologicalSex.Other));
                }
                else
                {
                    throw new Exception("User has not provided -- or has not allowed access to -- their biological sex.");
                }
            }
            else
            {
                throw new Exception("Error reading biological sex:  " + error.Description);
            }

            return(data);
        }
        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);
        }
Пример #6
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() }
            }));
        }
        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);
        }
Пример #8
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);
            }
        }
        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);
        }
Пример #10
0
        protected override IEnumerable <Datum> Poll(CancellationToken cancellationToken)
        {
            List <Datum> data = new List <Datum>();

            NSError error;
            NSDate  dateOfBirth = HealthStore.GetDateOfBirth(out error);

            if (error == null)
            {
                if (dateOfBirth == null)
                {
                    throw new Exception("User has not provided -- or has not allowed access to -- their date of birth.");
                }
                else
                {
                    data.Add(new BirthdateDatum(DateTimeOffset.Now, new DateTimeOffset(dateOfBirth.ToDateTime())));
                }
            }
            else
            {
                throw new Exception("Error reading date of birth:  " + error.Description);
            }

            return(data);
        }
        void UpdateJournal(object sender, EventArgs args)
        {
            var calendar = NSCalendar.CurrentCalendar;

            var startDate = DateTime.Now.Date;
            var endDate   = startDate.AddDays(1);

            var sampleType = HKSampleType.GetQuantityType(HKQuantityTypeIdentifierKey.DietaryEnergyConsumed);
            var predicate  = HKQuery.GetPredicateForSamples((NSDate)startDate, (NSDate)endDate, HKQueryOptions.None);

            var query = new HKSampleQuery(sampleType, predicate, 0, new NSSortDescriptor[0], (resultQuery, results, error) => {
                if (error != null)
                {
                    Console.WriteLine("An error occured fetching the user's tracked food. " +
                                      "In your app, try to handle this gracefully. The error was: {0}.", error.LocalizedDescription);
                    return;
                }

                InvokeOnMainThread(() => {
                    FoodItems.RemoveAllObjects();
                    foreach (HKQuantitySample sample in results)
                    {
                        var foodName  = (NSString)sample.Metadata.Dictionary [HKMetadataKey.FoodType];
                        double joules = sample.Quantity.GetDoubleValue(HKUnit.Joule);
                        var foodItem  = FoodItem.Create(foodName, joules);

                        FoodItems.Add(foodItem);
                    }

                    TableView.ReloadData();
                });
            });

            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);
        }
        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);
        }
Пример #14
0
        protected override Task <List <Datum> > PollAsync(CancellationToken cancellationToken)
        {
            List <Datum> data = new List <Datum>();

            ManualResetEvent queryWait = new ManualResetEvent(false);
            Exception        exception = null;

            HealthStore.ExecuteQuery(new HKAnchoredObjectQuery(ObjectType as HKSampleType, null, (nuint)_queryAnchor, nuint.MaxValue, new HKAnchoredObjectResultHandler2(

                                                                   (query, samples, newQueryAnchor, error) =>
            {
                try
                {
                    if (error == null)
                    {
                        foreach (HKSample sample in samples)
                        {
                            Datum datum = ConvertSampleToDatum(sample);
                            if (datum != null)
                            {
                                data.Add(datum);
                            }
                        }

                        _queryAnchor = (int)newQueryAnchor;
                    }
                    else
                    {
                        throw new Exception("Error while querying HealthKit for " + ObjectType + ":  " + error.Description);
                    }
                }
                catch (Exception ex)
                {
                    exception = new Exception("Failed storing HealthKit samples:  " + ex.Message);
                }
                finally
                {
                    queryWait.Set();
                }
            })));

            queryWait.WaitOne();

            if (exception != null)
            {
                throw exception;
            }

            // let the system know that we polled but didn't get any data
            if (data.Count == 0)
            {
                data.Add(null);
            }

            return(Task.FromResult(data));
        }
Пример #15
0
        protected override IEnumerable <Datum> Poll(CancellationToken cancellationToken)
        {
            List <Datum> data = new List <Datum>();

            ManualResetEvent queryWait = new ManualResetEvent(false);
            Exception        exception = null;

            HealthStore.ExecuteQuery(new HKAnchoredObjectQuery(ObjectType as HKSampleType, null, (nuint)_queryAnchor, nuint.MaxValue, new HKAnchoredObjectResultHandler2(
                                                                   (query, samples, newQueryAnchor, error) =>
            {
                try
                {
                    if (error == null)
                    {
                        foreach (HKSample sample in samples)
                        {
                            Datum datum = ConvertSampleToDatum(sample);
                            if (datum != null)
                            {
                                data.Add(datum);
                            }
                        }

                        _queryAnchor = (int)newQueryAnchor;
                    }
                    else
                    {
                        throw new Exception("Error while querying HealthKit for " + ObjectType + ":  " + error.Description);
                    }
                }
                catch (Exception ex)
                {
                    exception = new Exception("Failed storing HealthKit samples:  " + ex.Message);
                }
                finally
                {
                    queryWait.Set();
                }
            })));

            queryWait.WaitOne();

            if (exception != null)
            {
                throw exception;
            }

            if (data.Count == 0)
            {
                throw new Exception("User has not provided -- or has not allowed access to -- any " + ObjectType + " information since last poll.");
            }

            return(data);
        }
Пример #16
0
        protected override IEnumerable <Datum> Poll(CancellationToken cancellationToken)
        {
            List <Datum> data = new List <Datum>();

            NSError           error;
            HKBloodTypeObject bloodType = HealthStore.GetBloodType(out error);

            if (error == null)
            {
                if (bloodType.BloodType == HKBloodType.ABNegative)
                {
                    data.Add(new BloodTypeDatum(DateTimeOffset.Now, BloodType.ABNegative));
                }
                else if (bloodType.BloodType == HKBloodType.ABPositive)
                {
                    data.Add(new BloodTypeDatum(DateTimeOffset.Now, BloodType.ABPositive));
                }
                else if (bloodType.BloodType == HKBloodType.ANegative)
                {
                    data.Add(new BloodTypeDatum(DateTimeOffset.Now, BloodType.ANegative));
                }
                else if (bloodType.BloodType == HKBloodType.APositive)
                {
                    data.Add(new BloodTypeDatum(DateTimeOffset.Now, BloodType.APositive));
                }
                else if (bloodType.BloodType == HKBloodType.BNegative)
                {
                    data.Add(new BloodTypeDatum(DateTimeOffset.Now, BloodType.BNegative));
                }
                else if (bloodType.BloodType == HKBloodType.BPositive)
                {
                    data.Add(new BloodTypeDatum(DateTimeOffset.Now, BloodType.BPositive));
                }
                else if (bloodType.BloodType == HKBloodType.ONegative)
                {
                    data.Add(new BloodTypeDatum(DateTimeOffset.Now, BloodType.ONegative));
                }
                else if (bloodType.BloodType == HKBloodType.OPositive)
                {
                    data.Add(new BloodTypeDatum(DateTimeOffset.Now, BloodType.OPositive));
                }
                else
                {
                    throw new Exception("User has not provided -- or has not allowed access to -- their blood type.");
                }
            }
            else
            {
                throw new Exception("Error reading blood type:  " + error.Description);
            }

            return(data);
        }
Пример #17
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()}.");
                        }
                    });
                }
            });
        }
Пример #18
0
        public void EndWorkout(DateTime endDate)
        {
            WorkoutEndDate = endDate;
            workoutButton.SetTitle("Begin Workout");
            activeEnergyBurnedLabel.SetText("0.0");
            if (CurrentQuery != null)
            {
                var query = CurrentQuery;
                HealthStore.StopQuery(query);
            }

            SaveWorkout();
        }
 public void GetUserAuthorizationIfNeeded()
 {
     if (IsHealthDataAvailable)
     {
         HealthStore.RequestAuthorizationToShare(HealthTypesToWrite(),
                                                 HealthTypesToRead(),
                                                 (success, error) => {
             if (!success || error != null)
             {
                 AlertManager.ShowError("Health Data", "Unable to access health data.");
             }
         });
     }
 }
Пример #20
0
        protected override Task <List <Datum> > PollAsync(CancellationToken cancellationToken)
        {
            List <Datum> data = new List <Datum>();

            NSError error;
            HKFitzpatrickSkinTypeObject skinType = HealthStore.GetFitzpatrickSkinType(out error);

            if (error == null)
            {
                if (skinType.SkinType == HKFitzpatrickSkinType.I)
                {
                    data.Add(new FitzpatrickSkinTypeDatum(DateTimeOffset.Now, FitzpatrickSkinType.TypeI));
                }
                else if (skinType.SkinType == HKFitzpatrickSkinType.II)
                {
                    data.Add(new FitzpatrickSkinTypeDatum(DateTimeOffset.Now, FitzpatrickSkinType.TypeII));
                }
                else if (skinType.SkinType == HKFitzpatrickSkinType.III)
                {
                    data.Add(new FitzpatrickSkinTypeDatum(DateTimeOffset.Now, FitzpatrickSkinType.TypeIII));
                }
                else if (skinType.SkinType == HKFitzpatrickSkinType.IV)
                {
                    data.Add(new FitzpatrickSkinTypeDatum(DateTimeOffset.Now, FitzpatrickSkinType.TypeIV));
                }
                else if (skinType.SkinType == HKFitzpatrickSkinType.V)
                {
                    data.Add(new FitzpatrickSkinTypeDatum(DateTimeOffset.Now, FitzpatrickSkinType.TypeV));
                }
                else if (skinType.SkinType == HKFitzpatrickSkinType.VI)
                {
                    data.Add(new FitzpatrickSkinTypeDatum(DateTimeOffset.Now, FitzpatrickSkinType.TypeVI));
                }
                else if (skinType.SkinType == HKFitzpatrickSkinType.NotSet)
                {
                    data.Add(new FitzpatrickSkinTypeDatum(DateTimeOffset.Now, FitzpatrickSkinType.NotSet));
                }
                else
                {
                    throw new Exception("User has not provided -- or has not allowed access to -- their fitzpatrick skin type.");
                }
            }
            else
            {
                throw new Exception("Error reading Fitzpatrick skin type:  " + error.Description);
            }

            return(Task.FromResult(data));
        }
Пример #21
0
 public void EndWorkout(DateTime endDate)
 {
     WorkoutEndDate = endDate;
     ResetUI();
     if (CurrentQuery != null)
     {
         var query = CurrentQuery;
         HealthStore.StopQuery(query);
     }
     if (HeartRateQuery != null)
     {
         HealthStore.StopQuery(HeartRateQuery);
     }
     SaveWorkout();
 }
        void SaveWeightIntoHealthStore(double value)
        {
            var weightQuantity = HKQuantity.FromQuantity(HKUnit.Pound, value);
            var weightType     = HKQuantityType.GetQuantityType(HKQuantityTypeIdentifierKey.BodyMass);
            var weightSample   = HKQuantitySample.FromType(weightType, weightQuantity, NSDate.Now, NSDate.Now, new NSDictionary());

            HealthStore.SaveObject(weightSample, (success, error) => {
                if (!success)
                {
                    Console.WriteLine("An error occured saving the weight sample {0}. " +
                                      "In your app, try to handle this gracefully. The error was: {1}.", weightSample, error.LocalizedDescription);
                    return;
                }

                UpdateUsersWeight();
            });
        }
        void SaveHeightIntoHealthStore(double value)
        {
            var heightQuantity = HKQuantity.FromQuantity(HKUnit.Inch, value);
            var heightType     = HKQuantityType.GetQuantityType(HKQuantityTypeIdentifierKey.Height);
            var heightSample   = HKQuantitySample.FromType(heightType, heightQuantity, NSDate.Now, NSDate.Now, new NSDictionary());

            HealthStore.SaveObject(heightSample, (success, error) => {
                if (!success)
                {
                    Console.WriteLine("An error occured saving the height sample {0}. " +
                                      "In your app, try to handle this gracefully. The error was: {1}.", heightSample, error);
                    return;
                }

                UpdateUsersHeight();
            });
        }
        public void RemoveStepCountEntry(StepCountEntry entry)
        {
            //Cast the entry as a HealthKitBloodGlucoseEntry...
            HealthKitStepCountEntry hkStepCountEntry = entry as HealthKitStepCountEntry;

            HealthStore.DeleteObject(hkStepCountEntry.StepCountSample, new Action <bool, NSError> ((success, error) => {
                if (!success || error != null)
                {
                    //NOTE: If this app didn't put the entry into the blood glucose list, then there will be an error on delete.
                    AlertManager.ShowError("Health Kit", "Unable to delete step count sample: " + error);
                }
                else
                {
                    //Woo! We properly removed the last entry, make sure that any listeners to the glucose states are properly updated.
                    RefreshQuantityValue(HKQuantityTypeIdentifierKey.StepCount, HKObjectType.GetQuantityType(HKQuantityTypeIdentifierKey.StepCount));
                }
            }));
        }
        private void RefreshCharacteristicValue(NSString characteristicTypeKey, HKCharacteristicType characteristicType)
        {
            if (characteristicTypeKey == HKCharacteristicTypeIdentifierKey.BiologicalSex)
            {
                NSError error         = null;
                var     biologicalSex = HealthStore.GetBiologicalSex(out error);
                if (error == null)
                {
                    DispatchQueue.MainQueue.DispatchAsync(() => {
                        var dataStore = StateDispatcher <HealthState> .State;

                        HealthStateMutator.MutateBiologicalSex(
                            dataStore, () => GetDisplayableBiologicalSex(biologicalSex.BiologicalSex));

                        StateDispatcher <HealthState> .Refresh();
                    });
                }
            }
        }
Пример #26
0
        private void StartOutdoorRun()
        {
            // Create a workout configuration
            var configuration = new HKWorkoutConfiguration()
            {
                ActivityType = HKWorkoutActivityType.Running,
                LocationType = HKWorkoutSessionLocationType.Outdoor
            };

            // Create workout session
            // Start workout session
            NSError error          = null;
            var     workoutSession = new HKWorkoutSession(configuration, out error);

            // Successful?
            if (error != null)
            {
                // Report error to user and return
                return;
            }

            // Create workout session delegate and wire-up events
            RunDelegate = new WorkoutDelegate(HealthStore, workoutSession);

            RunDelegate.Failed += () => {
                System.Diagnostics.Debug.WriteLine("Failed");
            };

            RunDelegate.Paused += () => {
                System.Diagnostics.Debug.WriteLine("Paused");
            };

            RunDelegate.Running += () => {
                System.Diagnostics.Debug.WriteLine("Running");
            };

            RunDelegate.Ended += () => {
                System.Diagnostics.Debug.WriteLine("Ended");
            };

            // Start session
            HealthStore.StartWorkoutSession(workoutSession);
        }
Пример #27
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();
            }
        }
Пример #28
0
    void Start()
    {
        Debug.Log("---------- START ----------");
        this.healthStore = this.GetComponent <HealthStore>();

        if (Application.platform != RuntimePlatform.IPhonePlayer)
        {
//			this.instructionLabel.fontSize = 20;
//			this.instructionLabel.color = Color.red;
//			this.instructionLabel.text = "To use this plugin, you MUST run on an iOS device or in the iOS Simulator. \nIt WILL NOT WORK in the editor.";
//
//			string error = "HealthKit only works on iOS devices! It will not work in the Unity Editor.";
//			this.errorLabel.text = error;
//			Debug.LogError(error);
        }
        else
        {
            this.healthStore.Authorize(this.types);
            this.ReadData();
        }
    }
        public void AddStepCountEntry(StepCountEntry entry)
        {
            var date         = new NSDate();
            var quantityType = HKObjectType.GetQuantityType(HKQuantityTypeIdentifierKey.StepCount);
            var countUnit    = HKUnit.Count;
            var quantity     = HKQuantity.FromQuantity(countUnit, entry.Count);
            var sample       = HKQuantitySample.FromType(quantityType, quantity, date, date);

            HealthStore.SaveObject(sample, new Action <bool, NSError>((success, error) => {
                if (!success || error != null)
                {
                    //There may have been an add error for some reason.
                    AlertManager.ShowError("Health Kit", "Unable to add step count sample: " + error);
                }
                else
                {
                    //Refresh all app wide blood glucose UI fields.
                    RefreshQuantityValue(HKQuantityTypeIdentifierKey.StepCount, quantityType);
                }
            }));
        }
        /// <summary>
        /// This method handles all the HealthKit gymnastics to add a blood glucose entry to the HealthKit data.
        /// </summary>
        /// <param name="entry">Entry.</param>
        public void AddBloodGlucoseEntry(BloodGlucoseEntry entry)
        {
            var date         = new NSDate();
            var quantityType = HKObjectType.GetQuantityType(HKQuantityTypeIdentifierKey.BloodGlucose);
            var mgPerDL      = HKUnit.FromString("mg/dL");
            var quantity     = HKQuantity.FromQuantity(mgPerDL, entry.BloodGlucoseValue);
            var sample       = HKQuantitySample.FromType(quantityType, quantity, date, date);

            HealthStore.SaveObject(sample, new Action <bool, NSError>((success, error) => {
                if (!success || error != null)
                {
                    //There may have been an add error for some reason.
                    AlertManager.ShowError("Health Kit", "Unable to add glucose sample: " + error);
                }
                else
                {
                    //Refresh all app wide blood glucose UI fields.
                    RefreshQuantityValue(HKQuantityTypeIdentifierKey.BloodGlucose, quantityType);
                }
            }));
        }