How do I integrate HealthKit data in Swift?

Integrating HealthKit data in Swift allows developers to access and manage health-related data within iOS applications. This guide provides insight into how to request permissions, read data, and write data to the HealthKit store.

HealthKit, Swift, iOS Development, Health Data, HealthKit Integration, Fitness, Wellness

// Import HealthKit import HealthKit // Create a Health Store let healthStore = HKHealthStore() // Request authorization to access health data func requestAuthorization() { guard let heartRateType = HKObjectType.quantityType(forIdentifier: .heartRate) else { return } let dataTypesToShare: Set = [] let dataTypesToRead: Set = [heartRateType] healthStore.requestAuthorization(toShare: dataTypesToShare, read: dataTypesToRead) { (success, error) in if success { print("Authorization successful") } else { print("Authorization failed with error: \(String(describing: error))") } } } // Read heart rate data func readHeartRateData() { guard let heartRateType = HKObjectType.quantityType(forIdentifier: .heartRate) else { return } let query = HKSampleQuery(sampleType: heartRateType, predicate: nil, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { (query, results, error) in if let results = results as? [HKQuantitySample] { for result in results { let heartRate = result.quantity.doubleValue(for: HKUnit(from: "count/min")) print("Heart Rate: \(heartRate)") } } else { print("Error reading heart rate data: \(String(describing: error))") } } healthStore.execute(query) }

HealthKit Swift iOS Development Health Data HealthKit Integration Fitness Wellness