ios - 从 HKSampleQuery(Swift 4) 访问元数据

标签 ios swift xcode apple-watch healthkit

所以我正在关注苹果文档 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/

相关文章:

swift - 如何知道何时在 .searchable 搜索窗口中点击 SwiftUI 键盘搜索按钮

ios - 在 segue 和 dismiss VC 之后,我失去了主 VC 的所有导出连接

ios - 架构 i386 : "_OBJC_CLASS_$_ZipException", 的 undefined symbol 引用自:错误

ios - nib/xib 文件是否适用于不同的 View Controller ?

iphone - UIButton 不显示 iOS6 中的文本

ios - 转换后日期无效 12 小时 -> 24 小时

iphone - 通过didReceive数据导入图片

ios 在时钟的圆形 View 上旋转和滑动图像

swift - 为什么这个函数给我一个 "Command Failed due to signal"错误?

swift - 如何防止文本编辑器在 SwiftUI 中滚动?