Swift HealthKit 연동
2022. 5. 31. 15:47ㆍ아이폰 개발
For swift 4.2
1) Get HealthKitPermission
import HealthKit
func getHealthKitPermission() {
delay(0.1) {
guard HKHealthStore.isHealthDataAvailable() else {
return
}
let stepsCount = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!
self.healthkitStore.requestAuthorization(toShare: [], read: [stepsCount]) { (success, error) in
if success {
print("Permission accept.")
}
else {
if error != nil {
print(error ?? "")
}
print("Permission denied.")
}
}
}
}
2) To get steps count for specific date
func getStepsCount(forSpecificDate:Date, completion: @escaping (Double) -> Void) {
let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!
let (start, end) = self.getWholeDate(date: forSpecificDate)
let predicate = HKQuery.predicateForSamples(withStart: start, end: end, options: .strictStartDate)
let query = HKStatisticsQuery(quantityType: stepsQuantityType, quantitySamplePredicate: predicate, options: .cumulativeSum) { _, result, _ in
guard let result = result, let sum = result.sumQuantity() else {
completion(0.0)
return
}
completion(sum.doubleValue(for: HKUnit.count()))
}
self.healthKitStore.execute(query)
}
func getWholeDate(date : Date) -> (startDate:Date, endDate: Date) {
var startDate = date
var length = TimeInterval()
_ = Calendar.current.dateInterval(of: .day, start: &startDate, interval: &length, for: startDate)
let endDate:Date = startDate.addingTimeInterval(length)
return (startDate,endDate)
}
How to use
self.getStepsCount(forSpecificDate: Date()) { (steps) in
if steps == 0.0 {
print("steps :: \(steps)")
}
else {
DispatchQueue.main.async {
print("steps :: \(steps)")
}
}
}