Slide 22
Slide 22 text
How to use
import HealthKit
class HealthKitManager {
let healthStore = HKHealthStore()
// HealthKitͷηοτΞοϓ
init() {
if HKHealthStore.isHealthDataAvailable() {
let allTypes = Set([HKObjectType.quantityType(forIdentifier: .stepCount)!])
healthStore.requestAuthorization(toShare: nil, read: allTypes) { (success, error) in
if !success {
// ΤϥʔϋϯυϦϯά
}
}
}
}
// ಛఆͷͷาΛऔಘ
func getSteps(forDate date: Date, completion: @escaping (Double) -> Void) {
guard let stepCountType = HKQuantityType.quantityType(forIdentifier: .stepCount) else {
completion(0)
return
}
let startOfDay = Calendar.current.startOfDay(for: date)
let endOfDay = Calendar.current.date(byAdding: .day, value: 1, to: startOfDay)
let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: endOfDay, options: .strictStartDate)
let query = HKStatisticsQuery(quantityType: stepCountType, quantitySamplePredicate: predicate, options: .cumulativeSum) { (query, statistics, error) in
var steps: Double = 0
if error != nil {
// ΤϥʔϋϯυϦϯά
} else if let quantity = statistics?.sumQuantity() {
steps = quantity.doubleValue(for: HKUnit.count())
}
DispatchQueue.main.async {
completion(steps)
}
}
healthStore.execute(query)
}
}