-
Notifications
You must be signed in to change notification settings - Fork 3
HealthStoreManager (Deprecated)
S025_신명섭 edited this page Dec 1, 2021
·
1 revision
import Foundation
import HealthKit
final class HealthStoreManager {
static let shared = HealthStoreManager()
private var healthStore: HKHealthStore?
private init() {
if HKHealthStore.isHealthDataAvailable() {
healthStore = HKHealthStore()
} else {
return
}
}
func requestAuthorization() {
guard let activeEnergyBurned = HKSampleType.quantityType(forIdentifier: .activeEnergyBurned),
let distanceWalkingRunning = HKSampleType.quantityType(forIdentifier: .distanceWalkingRunning),
let stepCount = HKSampleType.quantityType(forIdentifier: .stepCount) else { return }
let shareTypes = Set([activeEnergyBurned, distanceWalkingRunning, stepCount])
let readTypes = Set([activeEnergyBurned, distanceWalkingRunning, stepCount])
healthStore?.requestAuthorization(toShare: shareTypes, read: readTypes) { (success, error) in
guard error != nil,
success else { return }
}
}
func requestStatisticsCollectionQuery(type: HKQuantityType, predicate: NSPredicate, interval: DateComponents, anchorDate: Date, completion: @escaping (HKStatisticsCollection) -> Void) {
let query = HKStatisticsCollectionQuery(
quantityType: type,
quantitySamplePredicate: predicate,
options: .cumulativeSum,
anchorDate: anchorDate,
intervalComponents: interval
)
query.initialResultsHandler = { _, hkStatisticsCollection, _ in
if let hkStatisticsCollection = hkStatisticsCollection {
completion(hkStatisticsCollection)
}
}
healthStore?.execute(query)
}
func requestStatisticsQuery(type: HKQuantityType, predicate: NSPredicate, completion: @escaping (HKStatistics) -> Void) {
let query = HKStatisticsQuery(
quantityType: type,
quantitySamplePredicate: predicate,
options: [.cumulativeSum, .duration]) { _, statistics, _ in
if let statistics = statistics {
completion(statistics)
}
}
healthStore?.execute(query)
}
}