Write a post

Enjoy this post? Give Abdul Karim a like if it's helpful.

1

iOS Health App: Populating the Mindfulness Section

Published Feb 16, 2017
iOS Health App: Populating the Mindfulness Section

Introduction

In this article you will learn how we can use healthkit and make our health app more awesome! Not only can you read data in the iOS health app, but you can also write data into it — how cool is that!
Healthkit integration ios

Diving into Healthkit

The HealthKit framework was introduced at WWDC 2014 as a single place where apps can store, share, and read health-related data. The new Health app, which allows users to view the data, was one of the best features of iOS 8. If you want to learn more, click here.

There are many benefits and best practices when working with this exciting framework. Recently, I've had first-hand experience working with the HealthKit framework when I add support for HealthKit to one of my apps Aware. If you are considering using HealthKit in your own app, then this tutorial is for you.

Topics Covered Here

  1. Basics of HealthKit
  2. Populating Data on Healthkit Mindfulness Section

Getting Started

  • Download the starter Project here.
  • Open it up and check the simple timer application.

So what we're doing here is — we will set a timer when start our meditation and stop the timer when our meditation ends. We will then check whether the app has populated the data on healthKit or not. As simple as that.

Let's Get Started.png

OK — let's get started!

Open the starter project you have downloaded --> navigate to capabilities --> turn on the health kit (shown below) --> make sure you added the HealthKit to your App id in your Certificates (Otherwise you will see an error sign in you capability section of health kit. If it does happen, don't panic! Xcode is intelligent enough to handle it — just click on the "automatic sign in Xcode 8: and it will handle it like a pro)

Screen Shot 2017-02-07 at 11.42.43 AM.png

This action adds the HealthKit entitlement to the App ID, the HealthKit key to the info plist file, the HealthKit entitlement to the entitlements file, and links HealthKit.framework. It’s really cool, right?

Now open up the viewController file and link the framework

         import UIKit
         import HealthKit // this way
         class ViewController: UIViewController {
          ......
         }

and create a instance of HKHealthStore() like this

     import UIKit
     import HealthKit

     class ViewController: UIViewController {

     @IBOutlet weak var timerLabel: UILabel!
     @IBOutlet weak var healthBtn: UIButton!
    
     var startTime = TimeInterval()
     var timer:Timer = Timer()
     var endTime: Date!
     var alarmTime: Date!
    
     let healthStore = HKHealthStore()  //this way
     :..
     :.
     }

Make sure you're aware of the time that it takes for the app to ask for users' permission to when they can access the data (i.e. read/write). Make sure you have access to the data before jumping directly to the code. Once you've been granted access, add the following items to info.plist file of your Ccode:

 open up info.plist file and add these items:-
 1.Privacy - Health Share Usage Description
 2.Privacy - Health Update Usage Description

Plist info in Xcode.png

These two items will help users understand why we want their data and how we will utilize it to benifit them

 Now open up storyboard and link an action button so that when user click on that it will ask for permission when user click it, which will be like the below code
     @IBAction func activateHealthKit(_ sender: Any) {
     //here we will write the code to ask the permission
     }

Well done! Now paste the following code inside the @IBAction — dont worry I will walk you through what this does:

@IBAction func activateHealthKit(_ sender: Any) {
     let typestoRead = Set([
            HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.mindfulSession)!
            ])
        
      let typestoShare = Set([
            HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.mindfulSession)!
            ])
        
        self.healthStore.requestAuthorization(toShare: typestoShare, read: typestoRead) { (success, error) -> Void in
            if success == false {
                print("solve this error\(error)")
                NSLog(" Display not allowed")
            }
            if success == true {
                print("dont worry everything is good \(success)")
                NSLog(" Integrated SuccessFully")
            }
          }
        }

The first two parameters of typetoRead and typetoShare are set to reference HKObjectType. What we want to access can be defined on HKCategoryTypeIndentifier — we have asked the users to allow us access to mindfulSession here.

requestAuthorization (toShare: typestoShare, read: typestoRead) are sets, instances of Swift’s Set class, which is a type Set<HKObjectType>. To understand more about what we are requesting permission for, you need to know about the class hierarchy of a few key classes of the HealthKit framework:
click here to learn more .

Run the app and click on the button to check weather it is working or not. Once you've clicked on it, you will get a screen like this:

Feb-07-2017 12-21-30.gif

Since we've asked the users for thier permission, we can send their data to HealthKit. We don't have to worry whether the users will give the app permission to access their data — HealthKit will manage them automatically. Awesome right? No error handling and no concerns about crashing.

Now that everything is done, we will calculate and save it to HealthKit. It's important to know how we did it because if we fail to calculate the correct data, our app will be rejected by the app store. Therefore, our code should be appropriate and accurate.

Saving data in healthkit mindfulness section

func saveMindfullAnalysis() {
        
        // alarmTime and endTime are NSDate objects
        if let mindfulType = HKObjectType.categoryType(forIdentifier: .mindfulSession) {
            
            // we create our new object we want to push in Health app
            let mindfullSample = HKCategorySample(type:mindfulType, value: 0, start: self.alarmTime, end: self.endTime)
            
            // at the end, we save it
            healthStore.save(mindfullSample, withCompletion: { (success, error) -> Void in
                
                if error != nil {
                    // something happened
                    return
                }
                
                if success {
                    print("My new data was saved in HealthKit")
                    
                } else {
                    // something happened again
                }
                
            })
        
        }
        
    }

We have calculated the alarmTime/Start time and endTime, which are of NSDate object, in the code above. We have also created a new object that we want to push in the Health app. Don't forget to save it when you're done with it!

As simple as that!

We will call the function saveMindfullAnalysis() when users stop the timer:

  @IBAction func stopAction(_ sender: Any) {
        endTime = Date()
        saveMindfullAnalysis()
        timer.invalidate()
    }

That's it!🎉 Now open up the Health kit app,navigate to mindfullness, and check if data has populated our app.

Health Kit.gif

Get the full code here! Hope you enjoyed this session!

Thank you🙏🏼

If you're interested in learning more about iOS, read more posts or ask for live help here.


If you have any questions, generate an issue on github, e-mail me at abdul.karim002@gmail.com, or comment below!

Discover and read more posts from Abdul Karim
get started
Enjoy this post?

Leave a like and comment for Abdul

1
Be the first to share your opinion

Subscribe to our weekly newsletter