How to Integrate Healthkit Data in iPhone Fitness Apps

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.

Being a leading fitness app development services provider we have build many fitness applications. And have implemented advanced features using Healthkit data. So, here we are providing an iOS healthkit tutorial, with 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

hand icon Create a new application with the name “HealthApp”

create-a-new-project

hand icon Now enable HealthKit in the application by following the below steps

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

hand icon Now, add permission in info.plist

set-project-properties

hand icon 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()
}    
Copy to Clipboard

hand icon 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)
            }
        }
    }
}        
Copy to Clipboard

hand icon 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
        }
    }
}           
Copy to Clipboard

allow-app-permission

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

hand icon 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)
}               
Copy to Clipboard

hand icon 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"
}    
Copy to Clipboard

And, that’s it.

hand icon 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. This data can also be used when developing a meditation app for heart rate monitoring, mindful minutes tracking and more. 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 app idea and want to know more about the cost to develop a fitness app, you can contact us to hire iphone developers. One of our sales representatives will get back to you shortly with a proposed solution. The consultation is absolutely free of cost.

Bhaval Patel

Written by

Bhaval Patel is a Director (Operations) at Space-O Technologies. He has 20+ years of experience helping startups and enterprises with custom software solutions to drive maximum results. Under his leadership, Space-O has won the 8th GESIA annual award for being the best mobile app development company. So far, he has validated more than 300 app ideas and successfully delivered 100 custom solutions using the technologies, such as Swift, Kotlin, React Native, Flutter, PHP, RoR, IoT, AI, NFC, AR/VR, Blockchain, NFT, and more.