我正在创建一个Fitness health应用程序,其中必须从Health kit中显示用户的实时卡路里及其心率。我获得了权限。但是我不知道如何获取卡路里和心率。

这是代码的许可。

static let healthKitStore = HKHealthStore()

// MARK:- Health Kit Permissions :-
static func authorizeHealthKit() {

    // HKQuantityTypeIdentifierBodyMass - For Weight

    var shareTypes = Set<HKSampleType>()
    shareTypes.insert(HKSampleType.workoutType())
    shareTypes.insert(HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!)
    shareTypes.insert(HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)!)
    shareTypes.insert(HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)!)


    var readTypes = Set<HKObjectType>()
    readTypes.insert(HKObjectType.workoutType())
    readTypes.insert(HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!)
    readTypes.insert(HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)!)
    readTypes.insert(HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)!)

    healthKitStore.requestAuthorizationToShareTypes(shareTypes, readTypes: readTypes) { (success, error) -> Void in
        if success {
            print("success")

        } else {
            print("failure")

        }

        if let error = error {

            print(error)
        }
    }

}

获得成功后,我需要卡路里和心率,这些功能或代码我必须使用。像 Fitbit Apis 一样返回数据,或者有 Apple Api的可以返回数据吗?

最佳答案

检查此代码:

let tHeartRate = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)
            let tHeartRateQuery = HKSampleQuery(sampleType: tHeartRate!, predicate:.None, limit: 0, sortDescriptors: nil) { query, results, error in

                if results?.count > 0
                {
                    var string:String = ""
                    for result in results as! [HKQuantitySample]
                    {
                        let HeartRate = result.quantity
                        string = "\(HeartRate)"
                        print(string)
                    }
                }
}
self.healthKitStore.executeQuery(tHeartRateQuery)

关于ios - 如何从Swift中的Health Kit Sdk获取卡路里和心率?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40739920/

10-11 16:22