feat: Initial iOS Health Dashboard app (Swift + SwiftUI)
This commit is contained in:
32
PulseHealth/Services/HealthKitService.swift
Normal file
32
PulseHealth/Services/HealthKitService.swift
Normal file
@@ -0,0 +1,32 @@
|
||||
import HealthKit
|
||||
|
||||
class HealthKitService: ObservableObject {
|
||||
let healthStore = HKHealthStore()
|
||||
var isAvailable: Bool { HKHealthStore.isHealthDataAvailable() }
|
||||
|
||||
func requestAuthorization() async throws {
|
||||
let typesToRead: Set<HKObjectType> = [
|
||||
HKQuantityType(.heartRate),
|
||||
HKQuantityType(.restingHeartRate),
|
||||
HKQuantityType(.heartRateVariabilitySDNN),
|
||||
HKQuantityType(.stepCount),
|
||||
HKQuantityType(.activeEnergyBurned),
|
||||
HKQuantityType(.oxygenSaturation),
|
||||
HKCategoryType(.sleepAnalysis),
|
||||
]
|
||||
try await healthStore.requestAuthorization(toShare: [], read: typesToRead)
|
||||
}
|
||||
|
||||
func fetchTodaySteps() async -> Int {
|
||||
guard let type = HKQuantityType.quantityType(forIdentifier: .stepCount) else { return 0 }
|
||||
let now = Date()
|
||||
let startOfDay = Calendar.current.startOfDay(for: now)
|
||||
let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now)
|
||||
return await withCheckedContinuation { cont in
|
||||
let q = HKStatisticsQuery(quantityType: type, quantitySamplePredicate: predicate, options: .cumulativeSum) { _, result, _ in
|
||||
cont.resume(returning: Int(result?.sumQuantity()?.doubleValue(for: .count()) ?? 0))
|
||||
}
|
||||
healthStore.execute(q)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user