针对 Swift 4.2
1) 获取 HealthKit 权限
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) 获取特定日期的步数
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)
}
使用方法
self.getStepsCount(forSpecificDate: Date()) { (steps) in
if steps == 0.0 {
print("steps :: \(steps)")
}
else {
DispatchQueue.main.async {
print("steps :: \(steps)")
}
}
}