How to Integrate Healthkit Data while Developing Fitness Apps for iPhone (Tutorial)

how-to-use-HealthKit-data

Are you a healthcare startup or an entrepreneur from the fitness industry who wants to develop fitness apps for iPhone? Then, you must check this iOS tutorial about retrieving Healthkit Data to integrate within fitness mobile app.

In this iOS healthkit tutorial, we have shared a step-by-step guide on how to access health-related data from Apple healthkit devices and integrate it into your iPhone app development project.

Before starting with the iOS tutorial, let’s understand the basic concept of Apple HealthKit.

What is HealthKit?

During the WWDC 2014 event, Apple introduced HealthKit API within iOS 8. The purpose of introducing this API was to fix the issues related to healthkit compatible apps.

HealthKit API works as a repository on Apple devices to collect, store and organize all health-related data about a person’s physical, mental or spiritual state. With the user’s permission, all healthcare apps can communicate with the HealthKit store to fetch and share their health data.

The HealthKit framework allows iPhone app developers to utilize various health-related data and create an iPhone app of their own. Though some of the health data can only be provided by the user, while a few details like heart-pulse, blood pressure can be retrieved by iPhone developers to use.

Benefits of Healthkit

One of the main benefits of using Healthkit data in apple health apps is that it stores the health-related data and makes it available for other apps to retrieve and use as per requirement. Which means that we can gather health data related to exercise or running, or cycling and integrate it into our own fitness app for the iPhone.

However, there is some sensitive or personal information collected by Healthkit data, therefore to access or utilize any such data, an iPhone app must have user’s permission.

How it Works

This tutorial has been created using Swift 4 programming language, IDE – Xcode 9 and iOS 12. Using this HealthKit demo, we will create a simple fitness tracking app feature to learn the following:

  • How to request permission and fetch HealthKit data from different Apple devices
  • How to integrate HealthKit data into an iPhone app to display data

Here, we have explained one of the features known as steps count with detailed code and the demo.

Let’s Get Started

Step: 1

Create a new application with the name “HealthApp”

create-a-new-project

Now enable HealthKit in the application by following the below steps

Project Navigator -> Capabilities tab. Scroll down and toggle HealthKit “ON.”

Step: 2

Now, add permission in info.plist

set-project-properties

Step: 3

Now, create a shared instance class to manage HealthKit permission and other methods like fetch steps, sleep data etc.

Then, declare the HealthKit store object

class HealthKitAssistant {
    //Shared Variable    
    static let shared = HealthKitAssistant()
	
	//Healthkit store object
	let healthKitStore = HKHealthStore()

}

Step: 4

Now, create a permission block in shared instance class for access permission to fetch data from HealthKit.

//MARK: Permission block
    func getHealthKitPermission(completion: @escaping (Bool) -> Void) {
        
        //Check HealthKit Available
        guard HKHealthStore.isHealthDataAvailable() else {
            return
        }
        
        let stepsCount = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!
        
        self.healthKitStore.requestAuthorization(toShare: [stepsCount], read: [stepsCount]) { (success, error) in
            if success {
                completion(true)                
            } else {
                if error != nil {
                    print(error ?? "")
                }
                DispatchQueue.main.async {
                    completion(false)
                }
            }
        }
    }

Step: 5

Now, create a UITableViewController class by name “StepsTableViewController.swift”.

Call permission method from the shared instance.

class StepsTableViewController: UITableViewController {

	override func viewDidLoad() {
        super.viewDidLoad()
       
        //MARK: Get Healthkit permission 
        HealthKitAssistant.shared.getHealthKitPermission { (response) in
            //MARK: Permission response
        }
    }
}

allow-app-permission

Once we Allow permission, we can fetch data from HealthKit and do vice-versa.

Step: 6

We will add a new function in the shared class to fetch steps from HealthKit.

//MARK: - Get Recent step Data    
    func getMostRecentStep(for sampleType: HKQuantityType, completion: @escaping (_ stepRetrieved: Int, _ stepAll : [[String : String]]) -> Void) {
        
        // Use HKQuery to load the most recent samples.
        let mostRecentPredicate =  HKQuery.predicateForSamples(withStart: Date.distantPast, end: Date(), options: .strictStartDate)
        
        var interval = DateComponents()
        interval.day = 1
        
        let stepQuery = HKStatisticsCollectionQuery(quantityType: sampleType , quantitySamplePredicate: mostRecentPredicate, options: .cumulativeSum, anchorDate: Date.distantPast, intervalComponents: interval)
        
        stepQuery.initialResultsHandler = { query, results, error in
            
            if error != nil {
                //  Something went Wrong
                return
            }
            if let myResults = results {
                
                var stepsData : [[String:String]] = [[:]]
                var steps : Int = Int()
                stepsData.removeAll()
                
                myResults.enumerateStatistics(from: Date.distantPast, to: Date()) {
                    
                    statistics, stop in
                    
                    //Take Local Variable
                    
                    if let quantity = statistics.sumQuantity() {
                        
                        let dateFormatter = DateFormatter()
                        dateFormatter.dateFormat = "MMM d, yyyy"
                        dateFormatter.locale =  NSLocale(localeIdentifier: "en_US_POSIX") as Locale?
                        dateFormatter.timeZone = NSTimeZone.local
                        
                        var tempDic : [String : String]?
                        let endDate : Date = statistics.endDate
                        
                        steps = Int(quantity.doubleValue(for: HKUnit.count()))
                        
                        print("DataStore Steps = \(steps)")
                        
                        tempDic = [
                            "enddate" : "\(dateFormatter.string(from: endDate))",
                            "steps"   : "\(steps)"
                        ]
                        stepsData.append(tempDic!)
                    }
                }
                completion(steps, stepsData.reversed())
            }
        }
        HKHealthStore().execute(stepQuery)
    }

Step: 7

Now, we will fetch steps from “StepsTableViewController.swift” by calling a method from shared instance class and show in the table-view.

func loadMostRecentSteps()  {
        
        guard let stepsdata = HKQuantityType.quantityType(forIdentifier: .stepCount) else { return }
        
        HealthKitAssistant.shared.getMostRecentStep(for: stepsdata) { (steps , stepsData) in
            self.todayStep = steps
            self.stepDataSource = stepsData
            DispatchQueue.main.async {
                self.labelToday.text = "\(self.todayStep)"
            }
        }
    }


// MARK: - Table view data source
    /////////////////////////////////////////////
    

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return (stepDataSource?.count)!
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        // Configure the cell...
        
        cell.textLabel?.text =          (stepDataSource![indexPath.row] as AnyObject).object(forKey: "steps") as? String
        cell.detailTextLabel?.text =    (stepDataSource![indexPath.row] as AnyObject).object(forKey: "enddate") as? String
        
        return cell
    }
    
    
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "steps"
    }

And, that’s it.

OUTPUT

Conclusion

With this Apple Healthkit Data guide, we learned how to store steps count in an iPhone app. There are other features as well which we can include and consider while developing fitness app for iPhone.

Since the release of Apple Healthkit data, it is now easy to monitor day to day health data, whether it is counting steps or checks burnt calories, or tracking sleep time. We can also store the data as per our requirement.

By using Healthkit for iOS, we can retrieve and integrate data which is already saved in the healthkit store and develop fitness app of our own. Thus, it saves a lot of time in fetching different records.

You can download the source of this iOS app tutorial from Github. Moreover, if you have any such fitness app idea and looking to convert it into a fitness iPhone app, you can get in touch with us through our contact us form. One of our sales representatives will get back to you shortly with a proposed solution. The consultation is absolutely free of cost.

This page was last edited on March 15th, 2019, at 1:54.
 
 

Have an App Idea?

Get your free consultation now

Leave a Reply

Your email address will not be published. Required fields are marked *