1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
import SwiftUI import HealthKit class HeartRateManager: ObservableObject { let healthStore = HKHealthStore() @Published var heartRate: Double = 0.0 var query: HKObserverQuery? var isMonitoring = false func startHeartRateMonitoring() { guard HKHealthStore.isHealthDataAvailable() else { print("HealthKit no está disponible en este dispositivo") return } let readTypes: Set<HKObjectType> = [HKObjectType.quantityType(forIdentifier: .heartRate)!] healthStore.requestAuthorization(toShare: nil, read: readTypes) { [weak self] (success, error) in guard let self = self, success else { print("No se pudo obtener acceso a los datos de frecuencia cardíaca: \(error?.localizedDescription ?? "")") return } let heartRateType = HKObjectType.quantityType(forIdentifier: .heartRate)! self.query = HKObserverQuery(sampleType: heartRateType, predicate: nil) { [weak self] (query, completionHandler, error) in guard let self = self, self.isMonitoring else { return } let query = HKSampleQuery(sampleType: heartRateType, predicate: nil, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { (query, results, error) in if let samples = results as? [HKQuantitySample] { if let latestSample = samples.last { let pulse = latestSample.quantity.doubleValue(for: HKUnit.count().unitDivided(by: .minute())) DispatchQueue.main.async { self.heartRate = pulse } } } } self.healthStore.execute(query) completionHandler() } self.healthStore.execute(self.query!) self.isMonitoring = true } } func stopHeartRateMonitoring() { self.isMonitoring = false if let query = query { healthStore.stop(query) } } } struct ContentView: View { @StateObject var heartRateManager = HeartRateManager() var body: some View { VStack { Text("Frecuencia Cardíaca: \(heartRateManager.heartRate)") .padding() Button(action: { heartRateManager.startHeartRateMonitoring() }) { Text("Iniciar Medición") .padding() .foregroundColor(.white) .background(Color.blue) .cornerRadius(8) } } .onDisappear { heartRateManager.stopHeartRateMonitoring() } } } @main struct WatchApp: App { var body: some Scene { WindowGroup { ContentView() } } } |
Tener en cuenta:
- https://www.jesusninoc.com/01/01/missing-com-apple-developer-healthkit-entitlement/
- https://www.jesusninoc.com/01/01/anadir-capacidades-a-proyectos-en-xcode/