简体   繁体   中英

How to get the calories and heart rate from Health Kit Sdk in Swift?

I am creating an Fitness health app in which, I have to show user real time calories and their heart rate from Health kit. I get the permissions. But I don't know how to fetch the calories and heart rate.

Here is the permission of code.

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)
        }
    }

}

After getting success I need the calories and heart rate which function or which code I have to use. Like Fitbit Apis return the data or there is Apple Api's which will return the data?

Check this code:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM