public static Task <double> ReadCurrentHeightInMetres(HKHealthStore store)
        {
            var tcs = new TaskCompletionSource <double>();

            var heightType = HKQuantityTypeIdentifierKey.Height;
            var heightUnit = HKUnit.Meter;
            var sort       = new NSSortDescriptor(HKSample.SortIdentifierStartDate, false);

            var sampleType = HKObjectType.GetQuantityType(HKQuantityTypeIdentifierKey.Height);

            var query = new HKSampleQuery(sampleType, null, 1, new NSSortDescriptor[] { sort },
                                          (q, data, error) =>
            {
                if (error == null)
                {
                    var amount = (data[0] as HKQuantitySample).Quantity.GetDoubleValue(heightUnit);
                    tcs.TrySetResult(amount);
                }
                else
                {
                    tcs.TrySetException(new NSErrorException(error));
                }
            });

            store.ExecuteQuery(query);

            return(tcs.Task);
        }
        public bool RequestPermissions()
        {
            var stepsKey          = HKQuantityTypeIdentifierKey.StepCount;
            var stepsQuantityType = HKObjectType.GetQuantityType(stepsKey);

            _healthStore.RequestAuthorizationToShare(
                new NSSet(),
                new NSSet(new[] {
                stepsQuantityType
            }),
                (success, error) =>
            {
                if (success)
                {
                    StepQuery();
                }
                else
                {
                    Console.WriteLine(error);
                }
            }
                );

            return(true);
        }
Example #3
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);
                    }
                });
            }
        }
        static NSSet HealthTypesToWrite()
        {
            var quantityTypesToRead = QuantityTypesToRead.Select(q => HKObjectType.GetQuantityType(q));

            var allHealthTypesToRead = new List <object>();

            allHealthTypesToRead.AddRange(quantityTypesToRead);

            return(new NSSet(allHealthTypesToRead.ToArray()));
        }
Example #5
0
        private void ValidateAuthorization()
        {
            //Request / Validate that the app has permission to store heart-rate data
            var heartRateId   = HKQuantityTypeIdentifierKey.HeartRate;
            var heartRateType = HKObjectType.GetQuantityType(heartRateId);
            var typesToWrite  = new NSSet(new [] { heartRateType });
            //We aren't reading any data for this sample
            var typesToRead = new NSSet();

            healthKitStore.RequestAuthorizationToShare(
                typesToWrite,
                typesToRead,
                ReactToHealthCarePermissions);
        }
        public async Task <int> QueryTotalFlights()
        {
            var flightsCount         = HKObjectType.GetQuantityType(HKQuantityTypeIdentifierKey.FlightsClimbed);
            var sumOptions           = HKStatisticsOptions.CumulativeSum;
            int totalRecordetFlights = 0;
            var query = new HKStatisticsQuery(flightsCount, new NSPredicate(IntPtr.Zero), sumOptions, (HKStatisticsQuery resultQuery, HKStatistics results, NSError error) => {
                if (results != null)
                {
                    var quantitySample   = results;
                    totalRecordetFlights = (int)quantitySample.SumQuantity().GetDoubleValue(HKUnit.Count);
                    HealthKitDataContext.ActiveHealthKitData.DistanceReadings.TotalFlightsClimed = totalRecordetFlights;
                    Console.WriteLine(string.Format("totally walked {0} flights", totalRecordetFlights));
                }
            });
            await Task.Factory.StartNew(() => HealthKitStore.ExecuteQuery(query));

            return(totalRecordetFlights);
        }
        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));
                }
            }));
        }
        public async Task <string> QueryTotalStepsRecordingLastRecordingDate()
        {
            var    stepsCount   = HKObjectType.GetQuantityType(HKQuantityTypeIdentifierKey.StepCount);
            var    sumOptions   = HKStatisticsOptions.CumulativeSum;
            string resultString = string.Empty;
            var    query        = new HKStatisticsQuery(stepsCount, new NSPredicate(IntPtr.Zero), sumOptions, (HKStatisticsQuery resultQuery, HKStatistics results, NSError error) => {
                if (results != null)
                {
                    var quantitySample = results;
                    var quantity       = quantitySample.EndDate;
                    //	resultString = quantity.ToString();
                    HealthKitDataContext.ActiveHealthKitData.DistanceReadings.RecordingStoped = quantity.ToString();
                    Console.WriteLine(string.Format("Last recording of steps: {0} ", quantity.ToString()));
                }
            });
            await Task.Factory.StartNew(() => HealthKitStore.ExecuteQuery(query));

            return(resultString);
        }
        public async Task <double> QueryTotalLengthWalked()
        {
            var    stepsCount        = HKObjectType.GetQuantityType(HKQuantityTypeIdentifierKey.DistanceWalkingRunning);
            var    sumOptions        = HKStatisticsOptions.CumulativeSum;
            double totalLengthWalked = 0;
            var    query             = new HKStatisticsQuery(stepsCount, new NSPredicate(IntPtr.Zero), sumOptions, (HKStatisticsQuery resultQuery, HKStatistics results, NSError error) => {
                if (results != null)
                {
                    var quantitySample = results;
                    totalLengthWalked  = quantitySample.SumQuantity().GetDoubleValue(HKUnit.Meter);

                    HealthKitDataContext.ActiveHealthKitData.DistanceReadings.TotalDistance = totalLengthWalked;
                    Console.WriteLine(string.Format("totally walked {0}", totalLengthWalked));
                }
            });
            await Task.Factory.StartNew(() => HealthKitStore.ExecuteQuery(query));

            return(totalLengthWalked);
        }
Example #10
0
        //Note that this will be called on a background thread
        void ReactToHealthCarePermissions(bool success, NSError error)
        {
            /*
             * The success and error arguments specify whether the user interacted
             * with the permissions dialog. This sample doesn't use that information.
             */

            //Instead, the important thing is to confirm that we can write heart-rate data
            var access = healthKitStore.GetAuthorizationStatus(HKObjectType.GetQuantityType(HKQuantityTypeIdentifierKey.HeartRate));

            if (access.HasFlag(HKAuthorizationStatus.SharingAuthorized))
            {
                HeartRateModel.Instance.Enabled = true;
            }
            else
            {
                HeartRateModel.Instance.Enabled = false;
            }
        }
        public int StepQuery()
        {
            var dateComponents = new NSDateComponents();

            dateComponents.Day = -1;
            var cal       = new NSCalendar(NSCalendarType.ISO8601);
            var yesterday = cal.DateFromComponents(dateComponents);
            var predicate = HKQuery.GetPredicateForSamples(yesterday, new NSDate(), HKQueryOptions.None);
            var query     = new HKSampleQuery(HKObjectType.GetQuantityType(HKQuantityTypeIdentifierKey.StepCount),
                                              predicate,
                                              0,
                                              null,
                                              new HKSampleQueryResultsHandler((retQuery, results, error) => {
                Console.WriteLine(results.Length);
            }));

            _healthStore.ExecuteQuery(query);

            return(0);
        }
        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);
                }
            }));
        }
        public void SetUpPermissions()
        {
            var distanceQuantityType          = HKObjectType.GetQuantityType(HKQuantityTypeIdentifierKey.DistanceWalkingRunning);
            var stepsQuantityType             = HKObjectType.GetQuantityType(HKQuantityTypeIdentifierKey.StepCount);
            var flightsQuantityType           = HKObjectType.GetQuantityType(HKQuantityTypeIdentifierKey.FlightsClimbed);
            var heightQuantityType            = HKObjectType.GetQuantityType(HKQuantityTypeIdentifierKey.Height);
            var heartRateQuantityType         = HKObjectType.GetQuantityType(HKQuantityTypeIdentifierKey.HeartRate);
            var nikeFuelQuantityType          = HKObjectType.GetQuantityType(HKQuantityTypeIdentifierKey.NikeFuel);
            var dateOfBirthCharacteristicType = HKObjectType.GetCharacteristicType(HKCharacteristicTypeIdentifierKey.DateOfBirth);
            var sexCharacteristicType         = HKObjectType.GetCharacteristicType(HKCharacteristicTypeIdentifierKey.BiologicalSex);
            var bloodTypeCharacteristicType   = HKObjectType.GetCharacteristicType(HKCharacteristicTypeIdentifierKey.BloodType);

            if (m_healthKitStore == null)
            {
                HealthKitStore = new HKHealthStore();
                m_healthKitStore.RequestAuthorizationToShare(new NSSet(new [] { distanceQuantityType, stepsQuantityType, flightsQuantityType, heartRateQuantityType }), new NSSet(new [] { (NSObject)distanceQuantityType, (NSObject)stepsQuantityType, (NSObject)flightsQuantityType, (NSObject)heightQuantityType, (NSObject)dateOfBirthCharacteristicType, (NSObject)sexCharacteristicType, (NSObject)bloodTypeCharacteristicType, (NSObject)nikeFuelQuantityType, (NSObject)bloodTypeCharacteristicType, (NSObject)heartRateQuantityType }), (success, error) => {
                    Console.WriteLine("Authorized:" + success);
                    if (error != null)
                    {
                        Console.WriteLine("Authorization error: " + error);
                    }
                });
            }
        }
        public void Refresh()
        {
            var quantityTypesToRead = QuantityTypesToRead.Select(q => new { Key = q, QuantityType = HKObjectType.GetQuantityType(q) });

            foreach (var quantityTypeToRead in quantityTypesToRead)
            {
                RefreshQuantityValue(quantityTypeToRead.Key, quantityTypeToRead.QuantityType);
            }

            var characteristicTypesToRead = CharacteristicTypesToRead.Select(c => new { Key = c, CharacteristicType = HKObjectType.GetCharacteristicType(c) });

            foreach (var characteristicTypeToRead in characteristicTypesToRead)
            {
                RefreshCharacteristicValue(characteristicTypeToRead.Key, characteristicTypeToRead.CharacteristicType);
            }
        }
Example #16
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            #region UI controls
            statusLabel      = new UILabel(new RectangleF(10, 30, 300, 30));
            statusLabel.Text = "waiting...";

            heartRateLabel           = new UILabel(new RectangleF(10, 70, 150, 30));
            heartRateLabel.Font      = UIFont.BoldSystemFontOfSize(36);
            heartRateLabel.TextColor = UIColor.Red;

            heartRateUnitLabel = new UILabel(new RectangleF(160, 70, 150, 30));

            deviceNameLabel = new UILabel(new RectangleF(10, 120, 300, 30));

            connectButton = UIButton.FromType(UIButtonType.System);
            connectButton.SetTitle("Connect", UIControlState.Normal);
            connectButton.SetTitle("searching...", UIControlState.Disabled);
            connectButton.Enabled        = false;
            connectButton.Frame          = new RectangleF(10, 160, 300, 30);
            connectButton.TouchUpInside += ConnectToSelectedDevice;

            permissionsLabel = new UILabel(new RectangleF(10, 200, 300, 60));

            storeData       = UIButton.FromType(UIButtonType.System);
            storeData.Frame = new RectangleF(10, 250, 300, 30);
            storeData.SetTitle("requires permission", UIControlState.Disabled);
            storeData.SetTitle("Store in HealthKit", UIControlState.Normal);
            storeData.Enabled        = false;
            storeData.TouchUpInside += (sender, e) => {
                UpdateHealthKit(heartRateLabel.Text);                 // pretty hacky :)
            };

            Add(statusLabel);
            Add(heartRateLabel);
            Add(heartRateUnitLabel);
            Add(deviceNameLabel);
            Add(connectButton);
            Add(permissionsLabel);
            Add(storeData);
            #endregion

            InitializeCoreBluetooth();

            #region HealthKit
            // https://gist.github.com/lobrien/1217d3cff7b29716c0d3
            // http://www.knowing.net/index.php/2014/07/11/exploring-healthkit-with-xamarin-provisioning-and-permissions-illustrated-walkthrough/

            healthKitStore = new HKHealthStore();
            //Permissions
            //Request HealthKit authorization
            var heartRateId   = HKQuantityTypeIdentifierKey.HeartRate;
            var heartRateType = HKObjectType.GetQuantityType(heartRateId);
            //Request to write heart rate, read nothing...
            healthKitStore.RequestAuthorizationToShare(new NSSet(new [] { heartRateType }), new NSSet(), (success, error) =>
                                                       InvokeOnMainThread(() => {
                if (success)
                {
                    //Whatever...
                    Console.WriteLine("RequestAuthorizationToShare: success");
                    permissionsLabel.Text = "HealthKit access is enabled!";
                    storeData.Enabled     = true;
                }
                else
                {
                    //Whatever...
                    Console.WriteLine("RequestAuthorizationToShare:  failed");
                    permissionsLabel.Text = "No permission to access HealthKit :-(";
                    storeData.Enabled     = false;
                }
                if (error != null)
                {
                    Console.WriteLine("HealthKit authorization error: " + error);
                }
            }));
            #endregion
        }