Swift - Get Glucose Data from Apple HealthKit

I am doing some tutorials on how to send and receive data to and from the Apple HealthKit app.

The part of the tutorial I'm doing is how to get the height from healthKitStore.

I want to do the same, but for getting glucose data instead of altitude, I did all the steps but got stuck in this piece of code:

var heightLocalizedString = self.kUnknownString;
        self.height = mostRecentHeight as? HKQuantitySample;
        // 3. Format the height to display it on the screen
        if let meters = self.height?.quantity.doubleValueForUnit(HKUnit.meterUnit()) {
            let heightFormatter = NSLengthFormatter()
            heightFormatter.forPersonHeightUse = true;
            heightLocalizedString = heightFormatter.stringFromMeters(meters);
        }

      

As shown, the var counters are assigned a double value from the counter, and then a constant formatter is created to format the var counters and assigned to the previously declared var (heightLocalizedString)

My question is, when I use this method to read glucose, I have to face several problems, the first problem is that I cannot figure out which units of glucose are available, the only one I get is

HKUnitMolarMassBloodGlucose

      

and when i use it the error appears: "NSNumber" is not a subtype of "HKUnit" , it clears the error, this parameter is not a subtype of the class HKUnit

.

Another problem is that, as shown in the previous code, there is a formatter for height (NSLengthFormatter())

, but I don't see such a format for glucose.

In fact, I'm not sure if you need to follow the exact guide to get your glucose data, but I also don't see any other way to do this.

Any ideas please?

Here is the code I'm using to get my glucose data:

func updateGluco(){

    let sampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodGlucose)
    self.healthManager?.readMostRecentSample(sampleType, completion: {(mostRecentGluco, error) -> Void in

        if (error != nil){
            println("Error reading blood glucose from HealthKit store: \(error.localizedDescription)")
            return;
        }

        var glucoLocalizedString = self.kUnknownString;
        self.gluco = mostRecentGluco as? HKQuantitySample
        println("\(self.gluco?.quantity.doubleValueForUnit(HKUnit.moleUnitWithMolarMass(HKUnitMolarMassBloodGlucose)))")
        self.gluco?.quantity.doubleValueForUnit(HKUnit.moleUnitWithMolarMass(HKUnitMolarMassBloodGlucose))
        if let mmol = self.gluco?.quantity.doubleValueForUnit(HKUnit.moleUnitWithMolarMass(HKUnitMolarMassBloodGlucose)) {
            glucoLocalizedString = "\(mmol)"
        } else {
            println("error reading gluco data!")
        }
        dispatch_async(dispatch_get_main_queue(), {() -> Void in
        self.glucoLabel.text = glucoLocalizedString})
    })
}

      

The variable "mmol" returns nil.

I don't know if this applies to my problem, but I just read an article that says Apple has returned blood glucose tracking in iOS 8.2 and my deployment target is 8.1. (I cannot update the deployment target to the latest iOS, even though Xcode is updated to the latest version!)

+3


source to share


3 answers


In the title, the meter requires units of type (mass / volume), which means you need to specify a composite block with the mass block divided by the volume unit:

HK_EXTERN NSString * const HKQuantityTypeIdentifierBloodGlucose NS_AVAILABLE_IOS(8_0);              // Mass/Volume,                 Discrete

      

Typical units of measurement for blood glucose are mg / dL and mmol / L. You can build them using:



HKUnit *mgPerdL = [HKUnit unitFromString:@"mg/dL"];

HKUnit *mmolPerL = [[HKUnit moleUnitWithMetricPrefix:HKMetricPrefixMilli molarMass:HKUnitMolarMassBloodGlucose] unitDividedByUnit:[HKUnit literUnit]];

      

Note that doubleValueForUnit: requires HKUnit, not NSNumber. See Additional Information

+3


source


I figured out the solution

In order to get the actual value of the sample gulco

, I have to use this property:, self.gluco?.quantity

exactly what I wanted before.



The default unit for glucose in HealthKit

is mg\dL

, to change the block, I simply extract the value of the number from the result and then divide it by 18.

0


source


Here is the code I'm using to get my glucose data:

 NSInteger limit = 0;
    NSPredicate* predicate = [HKQuery predicateForSamplesWithStartDate:[NSDate date] endDate:[NSDate date] options:HKQueryOptionStrictStartDate];;
    NSString *endKey =  HKSampleSortIdentifierEndDate;
    NSSortDescriptor *endDate = [NSSortDescriptor sortDescriptorWithKey: endKey ascending: NO];
    HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType: [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBloodGlucose]
                                                           predicate: predicate
                                                               limit: limit
                                                     sortDescriptors: @[endDate]
                                                      resultsHandler:^(HKSampleQuery *query, NSArray* results, NSError *error)
                            {
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    // sends the data using HTTP
                                    // Determine the Blood Glucose.
                                    NSLog(@"BloodGlucose=%@",results);

                                    if([results count]>0){
                                        NSMutableArray *arrBGL=[NSMutableArray new];
                                        for (HKQuantitySample *quantitySample in results) {
                                            HKQuantity *quantity = [quantitySample quantity];
                                            double bloodGlucosegmgPerdL = [quantity doubleValueForUnit:[HKUnit bloodGlucosegmgPerdLUnit]];
                                            NSLog(@"%@",[NSString stringWithFormat:@"%.f g",bloodGlucosegmgPerdL]);

                                        }
                                    }

                                });

                            }];

    [self.healthStore executeQuery:query];

// And Units :

@implementation HKUnit (HKManager)
+ (HKUnit *)heartBeatsPerMinuteUnit {
    return [[HKUnit countUnit] unitDividedByUnit:[HKUnit minuteUnit]];
}
+ (HKUnit *)bloodGlucosegmgPerdLUnit{
    return [[HKUnit gramUnit] unitDividedByUnit:[HKUnit literUnit]];
}

      

0


source







All Articles