UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Need Help pulling HealthKit Data and saving into CoreData to display

Forums > SwiftUI

I am building a sleep app that helps track your sleep mostly for sleep apnea individuals. I have already coded it to save variables into Coredata when you click the add button. And I already have it connected to HealthKit with permissions through a class called 'HealthHelper.' However, Im confused how to pull data from HealthKit and attach it into the Coredata entry when my user clicks on the add button. I want to do this so that I can save all my regular user input variables with the info pulled from HealthKit, so it is one entry into the Coredata entity for the app to read. I am trying to save the following variables from HealthKit (sleep analysis such as time in bed vs time asleep, heart rate, O2, height, and body mass(weight)). Any help is greatly appreciated. My function for querying the Healthkit data is below, but Im confused how to get the values now to put into Coredata.

public func grabMostRecentHKSamples(for sampleType: HKSampleType,
                           completion: @escaping (HKQuantitySample?, Error?) -> Swift.Void) {
        let mostRecentPredicate = HKQuery.predicateForSamples(withStart: Date.distantPast,
                                                              end: Date(),
                                                              options: [])

        let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate,
                                              ascending: true)
        let limit = 1
        let sampleQuery = HKSampleQuery(sampleType: sampleType,
                                        predicate: mostRecentPredicate,
                                        limit: limit,
                                        sortDescriptors: [sortDescriptor]) { (query, results, error) in

            DispatchQueue.main.async {

               if let result = results?.last as? HKQuantitySample {
                }
            }
        }

        HKHealthStore().execute(sampleQuery)
        print("HealthKit Sample grab complete")
    }

1      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.