Last active
January 1, 2023 15:05
-
-
Save KrishanMadushanka/177182a391ffa27b892074aa718a3d0d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import SwiftUI | |
| import HealthKit | |
| struct ContentView: View { | |
| @EnvironmentObject var healthStore: HKHealthStore | |
| var body: some View { | |
| VStack { | |
| Image(systemName: "globe") | |
| .imageScale(.large) | |
| .foregroundColor(.accentColor) | |
| Text("Hello, world!") | |
| } | |
| .padding() | |
| .onAppear(){ | |
| readHeartRate() | |
| } | |
| } | |
| //MARK: - Read heart rate | |
| private func readHeartRate(){ | |
| let quantityType = HKObjectType.quantityType(forIdentifier: .heartRate)! | |
| let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false) | |
| let sampleQuery = HKSampleQuery.init(sampleType: quantityType, | |
| predicate: get24hPredicate(), | |
| limit: HKObjectQueryNoLimit, | |
| sortDescriptors: [sortDescriptor], | |
| resultsHandler: { (query, results, error) in | |
| guard let samples = results as? [HKQuantitySample] else { | |
| print(error!) | |
| return | |
| } | |
| for sample in samples { | |
| let mSample = sample.quantity.doubleValue(for: HKUnit(from: "count/min")) | |
| print("Heart rate : \(mSample)") | |
| } | |
| }) | |
| self.healthStore .execute(sampleQuery) | |
| } | |
| private func get24hPredicate() -> NSPredicate{ | |
| let today = Date() | |
| let startDate = Calendar.current.date(byAdding: .hour, value: -24, to: today) | |
| let predicate = HKQuery.predicateForSamples(withStart: startDate,end: today,options: []) | |
| return predicate | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment