如何从 HealthKit 获取元数据?

How to get metadata from HealthKit?

我正在开发一个从 HealthKit 应用程序读取不同健康数据的应用程序。

至此我拿到了DOB,最近的身高、体重和血糖记录。

我还需要的是如何获取这些对象的元数据,特别是我需要获取 date/time 记录已输入。

比如获取身高的记录,我用的是这个方法:

func updateHeight()
{
// 1. Construct an HKSampleType for Height
let sampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)

// 2. Call the method to read the most recent Height sample
self.healthManager?.readMostRecentSample(sampleType, completion: { (mostRecentHeight, error) -> Void in

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

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


  // 4. Update UI. HealthKit use an internal queue. We make sure that we interact with the UI in the main thread
  dispatch_async(dispatch_get_main_queue(), { () -> Void in
    self.heightLabel.text = heightLocalizedString
  });
})

}

如您所见,我正在创建一个 HKSampleType 常量,然后将其传递给一个名为 readMostRecentSample 的方法,该方法采用此参数,然后 returns 此样本类型的最新记录.

我试图打印返回对象的行,我得到了这个输出:

1.9 m "Health" metadata: { HKWasUserEntered = 1; } 2015-05-17 10:11:00 +0300 2015-05-17 10:11:00 +0300

如您所见,输出包括对象的元数据,但实际上我不能只提取日期。

我还发现有一个名为metadata的对象属性,我把它打印出来,但它只检索了一个布尔值,判断数据是否由用户输入(手动)或自动来自第三方: println(self.height?.metadata)

输出是: [HKWasUserEntered = 1]

如果有人能告诉我如何提取每个对象的元数据,我将不胜感激。

一个HKSample对象及其子类HKQuantitySample有2个存储日期信息的字段:startDateendDate。如果您正在尝试获取日期,那么您应该在此处查看。

Some samples—for example, body temperature—represent a single point in time. For these samples, both the start and the end date are the same, because they both refer to the point in time when the sample was taken.

Other samples—for example, step count—represent data over a time interval. Here, the sample should use different start and end dates. These dates mark the beginning and end of the sample’s time interval, respectively.

来自文档https://developer.apple.com/library/ios/documentation/HealthKit/Reference/HKSample_Class/index.html#//apple_ref/occ/instp/HKSample/startDate