【问题标题】:Swift - Get glucose data from Apple HealthKitSwift - 从 Apple HealthKit 获取葡萄糖数据
【发布时间】:2015-05-13 11:16:36
【问题描述】:

我正在做一些关于如何向 Apple HealthKit 应用发送和接收数据的教程。

我正在做的部分教程是如何从 healthKitStore 获取高度。

我想做同样的事情,但要检索葡萄糖数据而不是高度,我做了所有步骤,但卡在了这段代码:

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);
        }

如图所示,从meterUnit中为meters var分配一个double值,然后创建一个常量格式化程序来格式化meters var并将其分配给预先声明的var(heightLocalizedString)

我的问题是,当我使用这种方法读取葡萄糖时,我遇到了几个问题,第一个问题是我无法弄清楚可用的葡萄糖单位,我得到的唯一一个是

HKUnitMolarMassBloodGlucose

当我使用它时会出现错误提示 "'NSNumber' is not a subtype of 'HKUnit'",从错误中可以清楚地看出此参数不是HKUnit 类的子类型.

另一个问题是,如前面的代码所示,有一个高度 (NSLengthFormatter()) 的格式化程序,但我看不到 Glucose 的这种格式化程序。

实际上我不确定是否必须完全按照教程来获取葡萄糖数据,但我也没有看到其他方法。

有什么想法吗?

这是我用来检索葡萄糖数据的代码:

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})
    })
}

“mmol”变量返回零值。

我不知道这是否与我的问题有关,但我刚刚看到一篇文章说苹果在 iOS 8.2 中恢复了血糖跟踪,我的应用程序部署目标是 8.1。 (尽管 XCode 已更新到最新版本,但我无法将部署目标升级到最新的 iOS!)

【问题讨论】:

  • let molesOfBloodGlucose = HKUnit.moleUnitWithMolarMass(HKUnitMolarMassBloodGlucose)?文档:developer.apple.com/library/prerelease/ios/documentation/…: 。此外,这个问题与 Xcode 无关 - 请删除该标签。
  • 这个常数与葡萄糖量样本无关,我使用了这个代码:“self.gluco?.quantity.doubleValueForUnit(HKUnit.moleUnitWithMolarMass(HKUnitMolarMassBloodGlucose))”但我得到的是零价值@RoboticCat
  • 请编辑您的问题以包含您正在使用的实际代码而不是示例代码,并使用您获得nil 值的信息对其进行更新。此外,调试器告诉您有关nil 值的什么信息 - 您的代码的哪一部分导致了它?
  • 我已经添加了用于获取葡萄糖数据的实际代码,请您看一下,还请注意问题末尾的最后一条注释,谢谢@机器人猫

标签: ios swift healthkit


【解决方案1】:

查看标题,血糖需要类型单位(质量/体积),这意味着您需要指定一个复合单位,即质量单位除以体积单位:

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

通常,人们测量血糖的单位是 mg/dL 和 mmol/L。您可以使用以下方法构建它们:

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

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

注意 doubleValueForUnit: 需要一个 HKUnit,而不是一个 NSNumber。查看更多信息

【讨论】:

  • 谢谢@jrushing 的回答,其实我不熟悉Objective-C 语言,但我可以说我已经得到了你的答案
【解决方案2】:

我想出了解决办法

要得到样本gulco的实际值,我只需要使用这个属性:self.gluco?.quantity,这正是我之前想要的。

HealthKit 中 Glucose 的默认单位是 mg\dL,为了更改单位,我只需从结果中提取数值,然后将其除以 18。

【讨论】:

    【解决方案3】:

    这是我用来检索葡萄糖数据的代码:

     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]];
    }
    

    【讨论】:

    • 请正确格式化您的代码并添加此代码实际作用的说明
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-13
    • 2014-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    相关资源
    最近更新 更多