所以我正在关注苹果文档 here
我想做的是访问 HKSampleQuery 上的 HKMetadataKeyHeartRateMotionContext 键。如果 HrContext = 1 并且 hr 高于某个数字,我需要做一些事情。
代码如下:
func sampleQ() -> HKQuery{
let pre = HKQuery.predicateForSamples(withStart: Date().lastweek, end: nil)
let que = HKSampleQuery(sampleType: heartRateType, predicate: pre, limit: Int(HKObjectQueryNoLimit), sortDescriptors: nil) {
query, results, error in
guard let samples = results as? [HKQuantitySample] else {
fatalError("An error occured fetching the user's tracked food. In your app, try to handle this error gracefully. The error was: \(String(describing: error?.localizedDescription))");
}
print (samples)
for sample in samples {
print (sample)
guard let hrContext =
sample.metadata?[HKMetadataKeyHeartRateMotionContext] as? String else {
break
}
print(hrContext)
print (hrContext+"i am the context")
}
}
return que
}
然后代码在这里被执行:
func startToMeasure() {
self.healthStore.execute(self.createStreamingQuery())
self.healthStore.execute(self.sampleQ())
}
出于某种原因,我在日志中得到的只是正常的流式心率以及打印的元数据(尽管我无法访问它,并且它没有打印我的任何 hrContext 语句)
有什么建议吗?
最佳答案
心率运动上下文本身的值是一个 NSInteger
,因此不能转换为 String
- 这个整数可以映射到 HKHeartRateMotionContext
的枚举案例.
let context = sample.metadata?[HKMetadataKeyHeartRateMotionContext] as? NSNumber
关于ios - 从 HKSampleQuery(Swift 4) 访问元数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49021119/