我正在尝试使我的应用显示我今天完成的所有步骤。根据手机上的Health-Kit应用程序,我已经完成了6个步骤,但该应用程序告诉我0。这是我正在使用的完整代码:
import UIKit
import HealthKit
class ViewController: UIViewController {
@IBOutlet weak var stepsLabel: UILabel!
let healthStore = HKHealthStore()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
getTodaysSteps { (count) in
DispatchQueue.main.async {
self.stepsLabel.text = count.description
print("DONE: \(count)")
}
}
}
func getTodaysSteps(completion: @escaping (Double) -> Void) {
let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!
let now = Date()
let startOfDay = Calendar.current.startOfDay(for: now)
let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, 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()))
}
healthStore.execute(query)
}
}
在这里我想念什么吗? 代码来自:https://stackoverflow.com/a/44111542/10660554
答案 0 :(得分:-1)
您尝试过此解决方案吗?
func retrieveStepCount(completion: @escaping (_ stepRetrieved: Double) -> Void) {
// Define the Step Quantity Type
let stepsCount = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)
// Get the start of the day
let date = Date()
let cal = Calendar(identifier: Calendar.Identifier.gregorian)
let newDate = cal.startOfDay(for: date)
// Set the Predicates & Interval
let predicate = HKQuery.predicateForSamples(withStart: newDate, end: Date(), options: .strictStartDate)
var interval = DateComponents()
interval.day = 1
// Perform the Query
let query = HKStatisticsCollectionQuery(quantityType: stepsCount!, quantitySamplePredicate: predicate, options: [.cumulativeSum], anchorDate: newDate as Date, intervalComponents:interval)
query.initialResultsHandler = { query, results, error in
if error != nil {
// Something went Wrong
return
}
if let myResults = results{
let now = Date()
myResults.enumerateStatistics(from: newDate, to: now, with: { (statistics, stop) in
if let quantity = statistics.sumQuantity() {
let steps = quantity.doubleValue(for: HKUnit.count())
print("Steps = \(steps)")
completion(steps)
}
})
}
}
healthStore.execute(query)
}