Apple Health Frameworks

Nov 29 2022 Swift 5, iOS 15, Xcode 13

Part 3: Take Advantage of CareKit & ResearchKit

16. Save Body Temperature Using HealthKit

Episode complete

Play next episode

Save for later
About this episode
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 15. Learn More About HealthKit Next episode: 17. Make a Contact Page

This video Save Body Temperature Using HealthKit was last updated on Nov 29 2022

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a Professional subscription.

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.

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()[feverSample, tempSample]) { _, error in
        if error != nil {
          Logger.survey.error("Failed to write data to HK")
    SurveyViewModel.addBodyTemperatureToHealthKit(temp: feverValue.doubleValue, date: result.endDate)