HealthKit

HealthKit is a framework that is provided by apple that helps us in getting and managing user health-related data in a very easy and convenient way.

We can integrate HealthKit in any application just by a grant the application to get access to the HealthKit data. so, the user data was easily available to that application from the healthKit Database. The user itself decide which data user allow to access or not.

To Implement a health Kit in any application. We need to follow these steps :

  1. we need to add these two in info Plist.
  • Privacy – Health Share Usage Description
  • Privacy – Health Update Usage Description

we need to ask for permission from the user to access user HealthKit data. 

  let healthStore = HKHealthStore()


  func askPermissionAndFetchHealthKitData() {

        

   let read = Set([HKObjectType.quantityType(forIdentifier : .steps)!])

  let share = Set([HKObjectType.quantityType(forIdentifier : .steps)!])

healthStore.requestAuthorization(toShare : share , read : read) { (check , error ) in 

If (chk) {

Print (“permission Granted ”)

    }

   }

}

 

So, with the above code, we got permission from the user to fetch steps. And that type of view appears on the screen 

We need to enable that permission of steps as shown in the above View.

3 . When the user got the permission we are here actually fetch the steps of the user.

func getStepsCount(forSpecificDate:Date, completion: @escaping (Double) -> Void) {

        let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!

        let (start, end) = self.getWholeDate(date: forSpecificDate)

        let predicate = HKQuery.predicateForSamples(withStart: start, end: end, options: .strictStartDate)

        let query = HKStatisticsQuery(quantityType: stepsQuantityType, quantitySamplePredicate: predicate, options: .cumulativeSum) { _, result, _ in

            guard let result = result, let sum = result.sumQuantity() else {

                completion(0.0)

                return

            }

            completion(sum.doubleValue(for: HKUnit.count()))

        }




        self.healthKitStore.execute(query)

    }




    func getWholeDate(date : Date) -> (startDate:Date, endDate: Date) {

        var startDate = date

        var length = TimeInterval()

        _ = Calendar.current.dateInterval(of: .day, start: &startDate, interval: &length, for: startDate)

        let endDate:Date = startDate.addingTimeInterval(length)

        return (startDate,endDate)

    }

We can get a Date by calling that above function like this :

self.getStepsCount(forSpecificDate: Date()) { (steps) in

                if steps == 0.0 {

                    print("steps :: \(steps)")

                }

                else {

                    DispatchQueue.main.async {

                        print("steps :: \(steps)")

                    }

                }

            }

These will give us the heartRate from startDate to endDate.

Steps: Optional(300.0)..

This is how we can calculate the steps through the healthKit. We can also calculate the heartRate, calories, and other elements through healthKit.

Kudos!

Leave a Reply