对于健康数据,HKMetadataKeyTimeZone始终为零,这是由Apple的健康应用程序创建的 - HealthKit - iOS [英] HKMetadataKeyTimeZone is always nil for health data which is created by apple's Health App - HealthKit - iOS

查看:181
本文介绍了对于健康数据,HKMetadataKeyTimeZone始终为零,这是由Apple的健康应用程序创建的 - HealthKit - iOS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用HealthKit阅读用户的健康数据。尝试从健康数据中获取时区信息,以确定健康活动发生在哪个确切时区。为此,我依赖于HealthKit元数据中的HKMetadataKeyTimeZone键。但是,即使对于Apple的Health应用程序自动记录的健康数据,'HKMetadataKeyTimeZone'键的值也总是为零。在Apple的Health应用程序中手动输入的数据也存在同样的问题。

I'm reading user's health data using HealthKit. Trying to get the timezone information from Health data to identify on which exact timezone the health activity has happened. For this, I'm depending on 'HKMetadataKeyTimeZone' key from HealthKit metadata. But the value for 'HKMetadataKeyTimeZone' key is always nil even for the health data that is automatically recorded by Apple's Health app. Same problem for the data that is manually entered on Apple's Health app.

那么是否有其他任何键/方式可以为每个样本提供时区信息?

So is there any other key/way that can give the time zone information for each sample?

或Apple的健康应用程序根本没有记录健康数据的时区信息?

or Apple's health app is not at all logging the timezone's information for health data?

或Apple的健康应用程序正在记录时区的健康数据信息,而不是通过HealthKit框架提供给开发人员?

or Apple's health app is logging the timezone's information for health data and not giving it to developers via HealthKit framework?

以下博客文章说,从HealthKit检索到的样本没有除非创建应用程序使用预定义的HKMetadataKeyTimeZone密钥在元数据属性中捕获该信息,否则与它们关联的时区信息。

即使Apple未能添加通过自己的Health应用程序生成的样本的时区元数据。

http://www.openmhealt h.org/3-painful-lessons-learned-building-with-healthkit/

以下是我的代码:

import HealthKit

let healthKitStore: HKHealthStore = HKHealthStore()


func getHealthDataValue_QuantityType(healthQuantityType : HKQuantityType?, strUnitType : String)
{
  if let healthQuantityType = healthQuantityType {
    if (HKHealthStore.isHealthDataAvailable()) {

      let query = HKAnchoredObjectQuery(type: healthQuantityType, predicate: nil, anchor: nil, limit: Int(HKObjectQueryNoLimit)) { (query, newSamples, deletedSamples, newAnchor, error) -> Void in

        guard let samples = newSamples as? [HKQuantitySample] else {
          print("newSamples are nil, Error: \(error?.localizedDescription ?? "")\n, identifier: \(healthQuantityType.identifier)")
          return
        }

        var healthKitData = [[String: Any]]()

        for quantitySample in samples {
          let quantity = quantitySample.quantity
          let healthDataUnit : HKUnit

          if (strUnitType.characters.count > 0 ) {
            healthDataUnit = HKUnit(from: strUnitType)
          } else {
            healthDataUnit = HKUnit.count()
          }

          let tempActualhealthData = quantity.doubleValue(for: healthDataUnit)

          var dicHealth = [String: Any]()
          dicHealth["StartDate"] = quantitySample.startDate.epoch()
          dicHealth["EndDate"] = quantitySample.endDate.epoch()

          dicHealth["TimeZone"] = getTimeZoneString(sample: quantitySample)
          dicHealth["Value"] = tempActualhealthData
          dicHealth["Unit"] = strUnitType
          dicHealth["Source"] = quantitySample.sourceRevision.source.name
          dicHealth["WasUserEntered"] = quantitySample.metadata?["HKWasUserEntered"] as? Int

          healthKitData.append(dicHealth)
        }

        print(healthKitData)
      }

      healthKitStore.execute(query)
    }
  }
}

extension Date {
  func epoch(isMilliSeconds: Bool = false) -> UInt64 {
    return UInt64(self.timeIntervalSince1970 * (isMilliSeconds ? 1000 : 1))
  }
}

func getTimeZoneString(sample: HKSample? = nil, shouldReturnDefaultTimeZoneInExceptions: Bool = true) -> String? {
  var timeZone: TimeZone?
    print("sample?.metadata?[HKMetadataKeyTimeZone]: \(sample?.metadata?[HKMetadataKeyTimeZone])") // I have steps data recorded by my iPhone6s, not getting the timezone information for that health data.

  if let metaDataTimeZoneValue = sample?.metadata?[HKMetadataKeyTimeZone] as? String {
    timeZone = TimeZone(identifier: metaDataTimeZoneValue)
  }

  if shouldReturnDefaultTimeZoneInExceptions == true && timeZone == nil {
    timeZone = TimeZone.current
  }

  var timeZoneString: String?

  if let timeZone = timeZone {
    let seconds = timeZone.secondsFromGMT()

    let hours = seconds/3600
    let minutes = abs(seconds/60) % 60

    timeZoneString = String(format: "%+.2d:%.2d", hours, minutes)
  }

  return timeZoneString
}


var healthKitTypesToRead = Set<HKObjectType>()
if let stepCountObject = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount) {
  healthKitTypesToRead.insert(stepCountObject)
}

healthKitStore.requestAuthorization(toShare: nil, read: healthKitTypesToRead) { (success, error) in
  if error == nil {
    getHealthDataValue_QuantityType(healthQuantityType: HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount), strUnitType: "count")
  }
}


推荐答案

没有别的办法。如果您认为在Health应用程序中手动输入的数据应该有一个,那么您应该向Apple提交错误与之相关的时区。

There is not a different way. You should file a bug with Apple if you think data manually entered in the Health app should have a timezone associated with it.

这篇关于对于健康数据,HKMetadataKeyTimeZone始终为零,这是由Apple的健康应用程序创建的 - HealthKit - iOS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆