Пример #1
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);
        }
Пример #3
0
        public override void SortDescriptorsChanged(NSTableView tableView, NSSortDescriptor[] oldDescriptors)
        {
            //base.SortDescriptorsChanged(tableView, oldDescriptors);

            //// Sort the data.
            //if (oldDescriptors.Length > 0)
            //{
            //    // Update sort.
            //    Sort(oldDescriptors[0].Key, oldDescriptors[0].Ascending);
            //}
            //else
            //{
            //    // Grab current descriptors and update sort.
            //    NSSortDescriptor[] sortDescriptor = tableView.SortDescriptors;
            //    Sort(sortDescriptor[0].Key, sortDescriptor[0].Ascending);
            //}

            // Grab current descriptors and update sort.
            NSSortDescriptor sortDescriptor = tableView.SortDescriptors.First(s => true);

            Sort(sortDescriptor.Key, sortDescriptor.Ascending);

            // Refresh table.
            tableView.ReloadData();
        }
Пример #4
0
 public GridTableView(string title, NSObject target)
 {
     Identifier   = title;
     RowSizeStyle = NSTableViewRowSizeStyle.Default;
     Enabled      = true;
     UsesAlternatingRowBackgroundColors = true;
     AutoresizesSubviews     = true;
     ColumnAutoresizingStyle = NSTableViewColumnAutoresizingStyle.None;
     WantsLayer = true;
     Layer      = new CALayer {
         Bounds = new CGRect(0, 0, 0, 0)
     };
     Bounds                      = new CGRect(0, 0, 0, 0);
     AutoresizingMask            = NSViewResizingMask.HeightSizable | NSViewResizingMask.WidthSizable;
     AllowsMultipleSelection     = false;
     AllowsColumnResizing        = true;
     AllowsColumnSelection       = false;
     AllowsColumnReordering      = false;
     SortDescriptors             = new NSSortDescriptor[] { };
     AutosaveName                = title;
     AutosaveTableColumns        = true;
     Target                      = target;
     DoubleAction                = new ObjCRuntime.Selector("ViewDetailsSelector");
     HeaderView.AutoresizingMask = NSViewResizingMask.WidthSizable;
 }
        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 override void SortDescriptorsChanged (NSTableView tableView, NSSortDescriptor[] oldDescriptors)
		{
			// Any sort direction given?
			if (oldDescriptors.Length <= 0)
				return;

			// Sort the data
			Sort (oldDescriptors [0].Key, oldDescriptors [0].Ascending);
			tableView.ReloadData ();
		}
        public override void SortDescriptorsChanged(NSTableView tableView, NSSortDescriptor[] oldDescriptors)
        {
            // Grab current descriptors and update sort.
            NSSortDescriptor sortDescriptor = tableView.SortDescriptors.First(s => true);

            Sort(sortDescriptor.Key, sortDescriptor.Ascending);

            // Refresh table.
            tableView.ReloadData();
        }
		public override void SortDescriptorsChanged (NSTableView tableView, NSSortDescriptor[] oldDescriptors)
		{
			// Sort the data
			if (oldDescriptors.Length > 0) {
				// Update sort
				Sort (oldDescriptors [0].Key, oldDescriptors [0].Ascending);
			} else {
				// Grab current descriptors and update sort
				NSSortDescriptor[] tbSort = tableView.SortDescriptors; 
				Sort (tbSort[0].Key, tbSort[0].Ascending); 
			}

			// Refresh table
			tableView.ReloadData ();
		}
Пример #9
0
        public void SortData(NSSortDescriptor[] descriptors)
        {
            NSIndexSet selections = tableView.SelectedRows;
            // Get a list of people to be removed
            List <Person> selectedPersons = new List <Person>();

            for (int i = 0; i < selections.Count; i++)
            {
                int    index = (int)selections.ElementAt(i);
                Person p     = Employees[index];
                selectedPersons.Add(p);
            }
            if (descriptors.Count <NSSortDescriptor>() > 0)
            {
                NSSortDescriptor descriptor = descriptors[0];
                if (descriptor.Key == "name")
                {
                    if (descriptor.Ascending)
                    {
                        _employees.Sort((emp1, emp2) => emp1.Name.ToLower().CompareTo(emp2.Name.ToLower()));
                    }
                    else
                    {
                        _employees.Sort((emp1, emp2) => emp2.Name.ToLower().CompareTo(emp1.Name.ToLower()));
                    }
                }
                else if (descriptor.Key == "expectedRaise")
                {
                    if (descriptor.Ascending)
                    {
                        _employees.Sort((emp1, emp2) => emp1.ExpectedRaise.CompareTo(emp2.ExpectedRaise));
                    }
                    else
                    {
                        _employees.Sort((emp1, emp2) => emp2.ExpectedRaise.CompareTo(emp1.ExpectedRaise));
                    }
                }
            }

            tableView.DeselectAll(this);
            foreach (Person p in selectedPersons)
            {
                tableView.SelectRow(Employees.IndexOf(p), true);
            }
        }
Пример #10
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);
        }
Пример #11
0
        public async Task <double> QueryTotalHeight()
        {
            var    heightType  = HKQuantityType.GetQuantityType(HKQuantityTypeIdentifierKey.Height);
            double usersHeight = 0.0;

            var timeSortDescriptor = new NSSortDescriptor(HKSample.SortIdentifierEndDate, false);
            var query = new HKSampleQuery(heightType, new NSPredicate(IntPtr.Zero), 1, new NSSortDescriptor[] { timeSortDescriptor },
                                          (HKSampleQuery resultQuery, HKSample[] results, NSError error) => {
                HKQuantity quantity = null;
                if (results.Length != 0)
                {
                    var quantitySample = (HKQuantitySample)results [results.Length - 1];
                    quantity           = quantitySample.Quantity;
                    usersHeight        = quantity.GetDoubleValue(HKUnit.Meter);
                    HealthKitDataContext.ActiveHealthKitData.Height = usersHeight;

                    Console.WriteLine(string.Format("height of Fetched: {0}", usersHeight));
                }
            });
            await Task.Factory.StartNew(() => HealthKitStore.ExecuteQuery(query));

            return(usersHeight);
        }
Пример #12
0
        public async Task <int> QueryLastRegistratedSteps()
        {
            var stepType             = HKQuantityType.GetQuantityType(HKQuantityTypeIdentifierKey.StepCount);
            int lastRegistratedSteps = 0;

            var timeSortDescriptor = new NSSortDescriptor(HKSample.SortIdentifierEndDate, false);
            var query = new HKSampleQuery(stepType, new NSPredicate(IntPtr.Zero), 1, new NSSortDescriptor[] { timeSortDescriptor },
                                          (HKSampleQuery resultQuery, HKSample[] results, NSError error) => {
                HKQuantity quantity = null;

                if (results.Length != 0)
                {
                    var quantitySample   = (HKQuantitySample)results [results.Length - 1];
                    quantity             = quantitySample.Quantity;
                    var source           = quantitySample.Source.Name;
                    lastRegistratedSteps = (int)quantity.GetDoubleValue(HKUnit.Count);
                    HealthKitDataContext.ActiveHealthKitData.DistanceReadings.TotalStepsOfLastRecording = lastRegistratedSteps;
                    HealthKitDataContext.ActiveHealthKitData.DistanceReadings.Source = source;
                }
            });

            m_healthKitStore.ExecuteQuery(query);
            return(lastRegistratedSteps);
        }
Пример #13
0
        public async Task <double> QueryLastRegistratedWalkingDistance()
        {
            var    distanceType = HKQuantityType.GetQuantityType(HKQuantityTypeIdentifierKey.DistanceWalkingRunning);
            double lastRegistratedWalkingDistance = 0.0;

            var timeSortDescriptor = new NSSortDescriptor(HKSample.SortIdentifierEndDate, false);
            var query = new HKSampleQuery(distanceType, new NSPredicate(IntPtr.Zero), 1, new NSSortDescriptor[] { timeSortDescriptor },
                                          (HKSampleQuery resultQuery, HKSample[] results, NSError error) => {
                HKQuantity quantity = null;
                string resultString = string.Empty;
                if (results.Length != 0)
                {
                    var quantitySample             = (HKQuantitySample)results [results.Length - 1];
                    quantity                       = quantitySample.Quantity;
                    lastRegistratedWalkingDistance = quantity.GetDoubleValue(HKUnit.Meter);

                    HealthKitDataContext.ActiveHealthKitData.DistanceReadings.TotalDistanceOfLastRecording = lastRegistratedWalkingDistance;
                    Console.WriteLine(string.Format("value of QueryLastRegistratedWalkingDistance: {0}", lastRegistratedWalkingDistance));
                }
            });

            m_healthKitStore.ExecuteQuery(query);
            return(lastRegistratedWalkingDistance);
        }
        void FetchData2(HKCategoryType 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);
        }
Пример #15
0
		public override void SortDescriptorsChanged (NSTableView tableView, NSSortDescriptor[] oldDescriptors)
		{
			// Sort the data
			Sort (oldDescriptors [0].Key, oldDescriptors [0].Ascending);
			tableView.ReloadData ();
		}
Пример #16
0
        public void Sections()
        {
            // https://bugzilla.xamarin.com/show_bug.cgi?id=13785

            // use Caches directory so this works with tvOS on devices (as well as existing iOS devices)
            string applicationDocumentsDirectory = NSSearchPath.GetDirectories(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomain.User, true).LastOrDefault();

            using (var ManagedObjectModel = new NSManagedObjectModel()) {
                {
                    // create an entity description
                    NSEntityDescription entity = new NSEntityDescription();
                    entity.Name = "Earthquake";

                    // create an attribute for the entity
                    NSAttributeDescription date = new NSAttributeDescription();
                    date.AttributeType = NSAttributeType.Date;
                    date.Name          = "date";
                    date.Optional      = false;

                    NSAttributeDescription latitude = new NSAttributeDescription();
                    latitude.AttributeType = NSAttributeType.Double;
                    latitude.Name          = "latitude";
                    latitude.Optional      = false;

                    NSAttributeDescription location = new NSAttributeDescription();
                    location.AttributeType = NSAttributeType.String;
                    location.Name          = "location";
                    location.Optional      = false;

                    NSAttributeDescription longitude = new NSAttributeDescription();
                    longitude.AttributeType = NSAttributeType.Double;
                    longitude.Name          = "longitude";
                    longitude.Optional      = false;

                    NSAttributeDescription magnitude = new NSAttributeDescription();
                    magnitude.AttributeType = NSAttributeType.Float;
                    magnitude.Name          = "magnitude";
                    magnitude.Optional      = false;

                    NSAttributeDescription USGSWebLink = new NSAttributeDescription();
                    USGSWebLink.AttributeType = NSAttributeType.String;
                    USGSWebLink.Name          = "USGSWebLink";
                    USGSWebLink.Optional      = false;

                    // assign the properties to the entity
                    entity.Properties = new NSPropertyDescription[] {
                        date,
                        latitude,
                        location,
                        longitude,
                        magnitude,
                        USGSWebLink
                    };

                    // add the entity to the model, and then add a configuration that
                    // contains the entities
                    ManagedObjectModel.Entities = new NSEntityDescription[] { entity };
                    ManagedObjectModel.SetEntities(ManagedObjectModel.Entities, String.Empty);
                }

                using (var PersistentStoreCoordinator = new NSPersistentStoreCoordinator(ManagedObjectModel)) {
                    {
                        var     storePath = applicationDocumentsDirectory + "/Earthquakes.sqlite";
                        var     storeUrl  = new NSUrl(storePath, false);
                        NSError error;

                        if (PersistentStoreCoordinator.AddPersistentStoreWithType(NSPersistentStoreCoordinator.SQLiteStoreType, null, storeUrl, null, out error) == null)
                        {
                            Assert.Fail("Unresolved error " + error + ", " + error.UserInfo);
                        }
                    }

                    using (var ManagedObjectContext = new NSManagedObjectContext()) {
                        ManagedObjectContext.PersistentStoreCoordinator = PersistentStoreCoordinator;

                        //					NSNotificationCenter.DefaultCenter.AddObserver (
                        //						this, new MonoTouch.ObjCRuntime.Selector ("mergeChanges"),
                        //						"NSManagedObjectContextDidSaveNotification", null);


                        NSFetchRequest      fetchRequest = new NSFetchRequest();
                        NSEntityDescription entity       = NSEntityDescription.EntityForName("Earthquake", ManagedObjectContext);
                        fetchRequest.Entity = entity;

                        NSSortDescriptor sortDescriptor = new NSSortDescriptor("date", false);
                        fetchRequest.SortDescriptors = new [] { sortDescriptor };

                        NSFetchedResultsController fetchedResultsController = new NSFetchedResultsController(
                            fetchRequest, ManagedObjectContext, null, null);

                        NSError error;

                        if (!fetchedResultsController.PerformFetch(out error))
                        {
                            Assert.Fail("Unresolved error: " + error + ", " + error.UserInfo);
                        }

                        var sections = fetchedResultsController.Sections;
                        Assert.That(sections [0].GetType().FullName, Is.StringEnding("CoreData.NSFetchedResultsSectionInfoWrapper"), "Wrapper");
                    }
                }
            }
        }
Пример #17
0
        public override void SortDescriptorsChanged(NSTableView tableView, NSSortDescriptor[] oldDescriptors)
        {
            NSSortDescriptor sortDescriptor = tableView.SortDescriptors[0];

            if (sortDescriptor != null)
            {
                Titles.Sort((x, y) =>
                {
                    switch (sortDescriptor.Key)
                    {
                    case "titleID":
                        return(string.Compare(x.titleID, y.titleID) * (sortDescriptor.Ascending ? 1 : -1));

                    case "titleName":
                        return(string.Compare(x.titleName, y.titleName) * (sortDescriptor.Ascending ? 1 : -1));

                    case "displayVersion":
                        return(string.Compare(x.displayVersion, y.displayVersion) * (sortDescriptor.Ascending ? 1 : -1));

                    case "versionString":
                        return(string.Compare(x.versionString, y.versionString) * (sortDescriptor.Ascending ? 1 : -1));

                    case "latestVersionString":
                        return(string.Compare(x.latestVersionString, y.latestVersionString) * (sortDescriptor.Ascending ? 1 : -1));

                    case "firmware":
                        return(string.Compare(x.firmware, y.firmware) * (sortDescriptor.Ascending ? 1 : -1));

                    case "masterkeyString":
                        return(string.Compare(x.masterkeyString, y.masterkeyString) * (sortDescriptor.Ascending ? 1 : -1));

                    case "filename":
                        return(string.Compare(x.filename, y.filename) * (sortDescriptor.Ascending ? 1 : -1));

                    case "filesizeString":
                        return((int)((x.filesize - y.filesize) * (sortDescriptor.Ascending ? 1 : -1)));

                    case "typeString":
                        return(string.Compare(x.typeString, y.typeString) * (sortDescriptor.Ascending ? 1 : -1));

                    case "distribution":
                        return(string.Compare(x.distribution.ToString(), y.distribution.ToString()) * (sortDescriptor.Ascending ? 1 : -1));

                    case "structureString":
                        return(string.Compare(x.structureString, y.structureString) * (sortDescriptor.Ascending ? 1 : -1));

                    case "signatureString":
                        return(string.Compare(x.signatureString, y.signatureString) * (sortDescriptor.Ascending ? 1 : -1));

                    case "permissionString":
                        return(string.Compare(x.permissionString, y.permissionString) * (sortDescriptor.Ascending ? 1 : -1));

                    case "error":
                        return(string.Compare(x.error, y.error) * (sortDescriptor.Ascending ? 1 : -1));

                    default:
                        return(0);
                    }
                });

                tableView.ReloadData();
            }
        }
Пример #18
0
 public void SortDescriptorsChanged(NSTableView tableView, NSSortDescriptor[] oldDescriptors)
 {
     SortData(tableView.SortDescriptors);
     tableView.ReloadData();
 }
Пример #19
0
        public void SortData(NSSortDescriptor[] descriptors)
        {
            NSIndexSet selections = tableView.SelectedRows;
            // Get a list of people to be removed
            List<Person> selectedPersons = new List<Person>();
            for (int i = 0; i < selections.Count; i++) {
                int index = (int)selections.ElementAt(i);
                Person p = Employees[index];
                selectedPersons.Add(p);
            }
            if (descriptors.Count<NSSortDescriptor>() > 0) {
                NSSortDescriptor descriptor = descriptors[0];
                if (descriptor.Key == "name") {
                    if (descriptor.Ascending)
                        _employees.Sort((emp1, emp2)=>emp1.Name.ToLower().CompareTo(emp2.Name.ToLower()));
                    else
                        _employees.Sort((emp1, emp2)=>emp2.Name.ToLower().CompareTo(emp1.Name.ToLower()));
                }
                else if (descriptor.Key == "expectedRaise") {
                    if (descriptor.Ascending)
                        _employees.Sort((emp1, emp2)=>emp1.ExpectedRaise.CompareTo(emp2.ExpectedRaise));
                    else
                        _employees.Sort((emp1, emp2)=>emp2.ExpectedRaise.CompareTo(emp1.ExpectedRaise));
                }
            }

            tableView.DeselectAll(this);
            foreach (Person p in selectedPersons) {
                tableView.SelectRow(Employees.IndexOf(p), true);
            }
        }
Пример #20
0
		public override void SortDescriptorsChanged (NSTableView tableView, NSSortDescriptor[] oldDescriptors)
		{
			// Sort the data
			if (oldDescriptors.Length > 0) {
				// Update sort
				Sort (oldDescriptors [0].Key, oldDescriptors [0].Ascendi
		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 RefreshQuantityValue(NSString quantityTypeKey, HKQuantityType quantityType)
        {
            NSSortDescriptor timeSortDescriptor = new NSSortDescriptor(HKSample.SortIdentifierEndDate, false);

            // Since we are interested in retrieving the user's latest sample, we sort the samples in descending order, and set the limit to 1. We are not filtering the data, and so the predicate is set to nil.
            HKSampleQuery query = new HKSampleQuery(quantityType, null, 100, new NSSortDescriptor[] { timeSortDescriptor },
                                                    new HKSampleQueryResultsHandler(new Action <HKSampleQuery, HKSample[], NSError>((query2, results, error) =>
            {
                if (results != null && results.Length > 0)
                {
                    if (quantityTypeKey == HKQuantityTypeIdentifierKey.Height)
                    {
                        //We have height, process the last entry into inches.
                        var quantitySample = results.LastOrDefault() as HKQuantitySample;

                        var quantity = quantitySample.Quantity;

                        var heightUnit = HKUnit.Inch;

                        DispatchQueue.MainQueue.DispatchAsync(() => {
                            var dataStore = StateDispatcher <HealthState> .State;

                            HealthStateMutator.MutateHeight(dataStore,
                                                            () => quantity.GetDoubleValue(heightUnit));

                            StateDispatcher <HealthState> .Refresh();
                        });
                    }
                    else if (quantityTypeKey == HKQuantityTypeIdentifierKey.StepCount)
                    {
                        DispatchQueue.MainQueue.DispatchAsync(() => {
                            //Now we need to deliver all the blood glucose entries in a list to any listeners.
                            var entries = new List <StepCountEntry>();

                            //Now also deliver all blood glucose readings up to the UI via the 'diff engine' for easy UITableViewController based updating.
                            foreach (var entry in results)
                            {
                                var sample = entry as HKQuantitySample;
                                if (sample != null)
                                {
                                    entries.Add(new HealthKitStepCountEntry(sample));
                                }
                            }

                            HealthStateDispatchers.StepCountListStateDispatcher.Refresh(
                                entries.Cast <StepCountEntry>().ToList());
                        });
                    }
                    else if (quantityTypeKey == HKQuantityTypeIdentifierKey.BloodGlucose)
                    {
                        DispatchQueue.MainQueue.DispatchAsync(() => {
                            //Refresh the views with the last known blood glucose quantity via HealthState and BloodGlucoseRecommendationState.
                            var lastBloodGlucoseQuantity = (results.LastOrDefault() as HKQuantitySample).Quantity;

                            var healthState = StateDispatcher <HealthState> .State;

                            var mgPerDL = HKUnit.FromString("mg/dL");
                            HealthStateMutator.MutateBloodGlucose(healthState,
                                                                  () => lastBloodGlucoseQuantity.GetDoubleValue(mgPerDL));


                            //At this point all UI subscribers to the HealthState object will update.
                            StateDispatcher <HealthState> .Refresh();



                            var recommendationStore = StateDispatcher <BloodGlucoseRecommendationState> .State;

                            BloodGlucoseRecommendationMutator.MutateBloodGlucose(
                                recommendationStore, () => healthState.BloodGlucose);

                            //At this point all UI subscribers to the BloodGlucoseRecommendationState will update.
                            StateDispatcher <BloodGlucoseRecommendationState> .Refresh();



                            //Now we need to deliver all the blood glucose entries in a list to any listeners.
                            var newBloodGlucoseEntries = new List <HealthKitBloodGlucoseEntry>();

                            //Now also deliver all blood glucose readings up to the UI via the 'diff engine' for easy UITableViewController based updating.
                            foreach (var bloodGlucoseEntry in results)
                            {
                                var bloodGlucoseSample = bloodGlucoseEntry as HKQuantitySample;
                                if (bloodGlucoseSample != null)
                                {
                                    newBloodGlucoseEntries.Add(new HealthKitBloodGlucoseEntry(bloodGlucoseSample));
                                }
                            }

                            HealthStateDispatchers.BloodGlucoseListStateDispatcher.Refresh(
                                newBloodGlucoseEntries.Cast <BloodGlucoseEntry>().ToList());
                        });
                    }
                }
            })));

            HealthStore.ExecuteQuery(query);
        }