首页 > 解决方案 > 如何为 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
                }

            })

        }


    }

我应该怎么办 ?

标签: swifthealthkit

解决方案


在代码文档中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)


推荐阅读