swift - 如何为 HealthKit 写正念记录?
问题描述
我正在尝试在健康应用程序中写下留心记录,但出现错误:
_HKObjectValidationFailureException',原因:'值 2 与 HKCategoryTypeIdentifierMindfulSession 类型不兼容
这是我的功能,金额是双倍的
func writeMindful() {
if let mindfulType = HKObjectType.categoryType(forIdentifier: .mindfulSession) {
let mindfullSample = HKCategorySample(type: mindfulType, value: Int(amount), start: Date(), end: Date() + amount)
// at the end, we save it
healthStore.save(mindfullSample, withCompletion: { (success, error) -> Void in
if error != nil {
// something happened
return
}
if success {
print("My new data was saved in HealthKit")
} else {
// something happened again
}
})
}
}
我应该怎么办 ?
解决方案
在代码文档中HKCategorySample
我们可以看到:
/** @property value @discussion The preferred enum for the value is determined by the receiver's category type. */ open var value: Int { get }
这意味着,每个类别都有自己的值枚举。MindfullSession 的这个枚举只有一个适用的值:HKCategoryValue.notApplicable
.
所以你的代码应该是这样的:
let mindfullSample = HKCategorySample(type: mindfulType, value: HKCategoryValue.notApplicable.rawValue, start: Date(), end: Date() + amount)
推荐阅读
- javascript - 使用 reduce 和 react hooks 的更好方法
- php - 如何在 PHP 5.6 版本中使用全局常量而不是类常量
- r - 如何将数据框中的所有 0 替换为诸如“。”之类的字符。或者 ”-”?
- c# - 带有 WPF managedhost 控件的 AX 表单无法再次打开
- sql - 创建 SQL 总计表
- lua - 我有 Luadec 的问题,错误:预编译块中的错误标头
- javascript - append() 是 jQuery 还是 Javascript 函数?
- laravel - 收集后Laravel无法展平数组->忘记
- javascript - 我怎样才能打开summernote要求?
- typescript - 如何使用 TypeScript 方法装饰器并保留正常的 `this` 范围