Part 3, Episode 16, Save body temperature into the HealthKit.
In this episode, I want to show you how to store data in the HealthKit.
Since we discussed HealthKit, CareKit, and ResearchKit, you should know there is no storage place for ResearchKit, so we have used CareKitStore to keep the result of surveys. There is also no connection between CareKit and HealthKit, and if you want to have any of those data in the HealthKit, you have to save the data coming from ResearchKit as a result of any survey into the HKHealthStore which you have already got access to it at the onboarding task.
Open SurveyViewModel.swift from project navigator and at the end of SurveyViewModel enum add this static function:
static func addBodyTemperatureToHealthKit(temp: Double?, date: Date) {
guard let quantityType = HKQuantityType.quantityType(forIdentifier: .bodyTemperature) else { return }
guard let categoryType = HKObjectType.categoryType(forIdentifier: .fever) else { return }
guard let temp = temp else { return }
let quanitytUnit = HKUnit(from: "degC" )
let quantityAmount = HKQuantity(unit: quanitytUnit, doubleValue: temp)
let tempSample = HKQuantitySample(type: quantityType, quantity: quantityAmount, start: date, end: date)
let feverSample = HKCategorySample(type: categoryType, value: Int((temp - 35 ) / 7.0 * 5), start: date, end: date)
if HKHealthStore.isHealthDataAvailable() {
let store = HKHealthStore()
store.save([feverSample, tempSample]) { _, error in
if error != nil {
Logger.survey.error("Failed to write data to HK")
}
}
}
}
Here you get the temperature as input and transfer it to two different samples to store it in the HKHealthStore.
First, initiate the types, make two different ones, one for fever and one for bodyTemperature. Since the body temperature is a Quantity type, you need a Unit for the next variable. After that, make the Quantity amount and then make the sample.
For the fever sample, if you look at the documentation, you will find out how to calculate it and make it meaningful, so I did that step for you.
After all the calculations, you check if the Health Data is available for you, meaning you have permission to read or write to HealthKit. For the last step, you save the data in the store, and you are done.
Now it’s the time to call this function; where do we have the fever data? Yes, you are right in the checkInSurveyOutcome function, scroll up and call this function right after // Call HealthKit function and booom, you just stored a data to the HealthKit.
SurveyViewModel.addBodyTemperatureToHealthKit(temp: feverValue.doubleValue, date: result.endDate)
Build and run and try to add new data in the CheckIn task and then navigate to Health app to see if it’s stored correctly or not.