How To Save Data To Apple Health in Swift

A tutorial to learn how to save health information to Apple Health

Domenico Nicoli
Dec 4 · 4 min read
Photo by William Hook on Unsplash

Apple Health is the health informatics app announced in 2014 and available with iOS 8 or later. HealthKit is the API included in the iOS SDK used by software developers to create applications that can save/read to the Apple Health application on iOS.

In this tutorial, I will explain how to save data and information to Apple Health with a few lines of code.


Getting Started

First, open Xcode and create a new project. Select Single View App.

Then create a new class and name it HealthKitAssistant. Here we put all the methods that we will be using to save data on Apple Health.

Go toMain.Storyboard file and add a DatePicker in the top, a TextField in the middle and a Button on the bottom of the screen.

Go to your project settings, select Signing & Capabilities and Add HealthKit to allow your app to ask user permission and then store/retrieve health information.

The last step you need to do in order to access user information is to add the following key in the Info.plist file:

<key>NSHealthShareUsageDescription</key>
<string>"Please give us the reading permission to allow the app to work."</string>
<key>NSHealthUpdateUsageDescription</key>
<string>"Please give us the update permission to add data into Apple Health."</string>

Implementation

First of all, we add the first method to HealthKitAssistantfile. This method is needed to request authorization from the users to read and write data from the device:

public class func authorizeHealthKit(completion: @escaping (Bool, Error?) -> Swift.Void) {
guard HKHealthStore.isHealthDataAvailable() else {
completion(false, HealthkitSetupError.notAvailableOnDevice)
return
}

guard let stepsCount = HKObjectType.quantityType(forIdentifier: .stepCount) else {
completion(false, HealthkitSetupError.dataTypeNotAvailable)
return
}

let healthKitTypesToWrite: Set<HKSampleType> = [stepsCount,
HKObjectType.workoutType()]

let healthKitTypesToRead: Set<HKObjectType> = [stepsCount,
HKObjectType.workoutType()]

HKHealthStore().requestAuthorization(toShare: healthKitTypesToWrite,
read: healthKitTypesToRead) { (success, error) in
completion(success, error)
}

}

Then we add a method to write steps data on Apple Health:

public class func saveSteps(stepsCountValue: Int,
date: Date,
completion: @escaping (Error?) -> Swift.Void) {

guard let stepCountType = HKQuantityType.quantityType(forIdentifier: .stepCount) else {
fatalError("Step Count Type is no longer available in HealthKit")
}

let stepsCountUnit:HKUnit = HKUnit.count()
let stepsCountQuantity = HKQuantity(unit: stepsCountUnit,
doubleValue: Double(stepsCountValue))

let stepsCountSample = HKQuantitySample(type: stepCountType,
quantity: stepsCountQuantity,
start: date,
end: date)

HKHealthStore().save(stepsCountSample) { (success, error) in

if let error = error {
completion(error)
print("Error Saving Steps Count Sample: \(error.localizedDescription)")
} else {
completion(nil)
print("Successfully saved Steps Count Sample")
}
}

}

Now on ViewController file, we will call the authorizeHealthKit method on viewDidLoad. A prompt message is shown to the user that gives our app read/write access permission to the health data.

HealthKitSetupAssistant.authorizeHealthKit { (result, error) in
if result {
print("Auth ok")
} else {
print("Auth denied")
}

}

Then on saveButton action add the following code:

@IBAction func saveButton(_ sender: Any) {
guard let value = textFieldValue.text else {
return
}

HealthKitSetupAssistant.saveSteps(stepsCountValue: Int(value)!, date: datePicker.date) { (error) in
print(error)
}

}

Test

We’re ready to test the app!

Run the simulator and allow health access to the app. Then, select a day and a time. Finally, write a value on the text field and tap the Save button.

If you open the Apple Health app now you will see a new record on the steps data!


Full Code

You can find the full code on GitHub with more data types, a method to read data and a method to delete data.

Thank you for reading. If you have any questions or suggestions, please let me know in the comments.

Better Programming

Advice for programmers.

Domenico Nicoli

Written by

Backend Developer (C#, VB.NET, Microsoft SQL Server), iOS developer (Swift). Parma, Italy 🇮🇹 https://linkedin.com/in/domenico-nicoli-5738ba15a

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade