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)
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?