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

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 15. Learn More About HealthKit Next episode: 17. Make a Contact Page

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

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