简体   繁体   English

Swift - 从Apple HealthKit获取葡萄糖数据

[英]Swift - Get glucose data from Apple HealthKit

I'm doing some tutorials about how to send and receive data to and from Apple HealthKit app. 我正在做一些关于如何向Apple HealthKit应用程序发送和接收数据的教程。

Part of the tutorial I'm doing is how to get the height from the healthKitStore. 我正在做的部分教程是如何从healthKitStore获取高度。

I want to do the same thing but to retrieve the glucose data instead of the height, I did all the steps but got stuck at 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 meters var is being assigned a double value from the meterUnit, and then creating a constant formatter to format the meters var and assign it to the pre-declared var (heightLocalizedString) 如图所示,meter var被分配一个来自meterUnit的double值,然后创建一个常量格式化器来格式化meter var并将其分配给预先声明的var(heightLocalizedString)

My question is, when I use this method for the glucose reading, I face a couple of issues, the first problem is I can't figure out what glucose units are available, the only one I get is 我的问题是,当我使用这种方法进行葡萄糖读数时,我面临一些问题,第一个问题是我无法弄清楚可用的葡萄糖单位是什么,我得到的唯一一个是

HKUnitMolarMassBloodGlucose

and when I use it an error appears says "'NSNumber' is not a subtype of 'HKUnit'" , it's clear from the error this parameter is not a subtype of the HKUnit class. 当我使用它时出现错误,显示“'NSNumber'不是'HKUnit'的子类型” ,从错误中可以清楚地看出这个参数不是HKUnit类的子类型。

Another issue is, as shown in the previous code there is a formatter for the height (NSLengthFormatter()) , but I can't see a such formatter for the Glucose. 另一个问题是,如前面的代码所示,有一个高度格式化程序(NSLengthFormatter()) ,但我看不到这样的格式化葡萄糖。

Actually I'm not sure if have to follow exactly the tutorial to get the Glucose data, but also I don't see another manner to do so. 实际上我不确定是否必须完全按照教程来获取葡萄糖数据,但我也没有看到另一种方法。

Any ideas please? 有什么想法吗?

Here is the code I'm using to retrieve the 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 "mmol" variable returns a nil value. “mmol”变量返回nil值。

I don't know if this relates to my problem, but I've just read an article said that Apple brought back blood glucose tracking in iOS 8.2 and my application deployment target is 8.1. 我不知道这是否与我的问题有关,但我刚读了一篇文章说Apple在iOS 8.2中带回了血糖跟踪,我的应用程序部署目标是8.1。 (I can't upgrade the deployment target to the latest iOS despite that the XCode is updated to the last release!) (尽管XCode已更新到上一版本,但我无法将部署目标升级到最新的iOS!)

Looking in the header, blood glucose requires units of the type (Mass / Volume), which means you need to specify a compound unit with a Mass unit divided by a Volume unit: 查看标题,血糖需要类型单位(质量/体积),这意味着您需要指定一个质量单位除以体积单位的复合单位:

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

Typically, the units that people measure blood glucose in are mg/dL, and mmol/L. 通常,人们测量血糖的单位是mg / dL和mmol / L. You can construct these by using: 您可以使用以下方法构造它们:

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

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

Note that doubleValueForUnit: requires an HKUnit, not an NSNumber. 请注意,doubleValueForUnit:需要HKUnit,而不是NSNumber。 See for more information 有关更多信息,请参阅

I figured out the solution 我找到了解决方案

To get the actual value of the sample gulco , I have only to use this property: self.gluco?.quantity , that's exactly what I wanted before. 为了获得样本gulco的实际价值,我只需要使用这个属性: self.gluco?.quantity ,这正是我之前想要的。

The default unit for the Glucose in HealthKit is mg\\dL , in order to change the unit simply I extract the number value from the result and then divide it by 18. HealthKit葡萄糖的默认单位是mg\\dL ,为了更改单位,我只需从结果中提取数字值,然后除以18。

Here is the code I'm using to retrieve the 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]];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM