无法获得今天显示标签的步骤

时间:2017-05-29 10:49:55

标签: ios swift xcode health-kit

我正在尝试创建一个标签,显示HealthKit今天的步骤。我已经允许HealthKit读取/写入数据,但我仍然坚持实际获取数据。

有人可以提供任何建议吗?这是我的代码,包括我想要显示步骤的标签:

import Foundation
import UIKit
import HealthKit


class HealthKitPage : UIViewController
{
      let healthStore: HKHealthStore = HKHealthStore()

      override func viewDidLoad()
      {
                var shareTypes = Set<HKSampleType>()

                shareTypes.insert(HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!)

                var readTypes = Set<HKObjectType>()
                readTypes.insert(HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!)


                healthStore.requestAuthorization(toShare: shareTypes, read: readTypes) { (success, error) -> Void in
                          if success {
                                    print("success")
                          } else {
                                    print("failure")
                          }

                          if let error = error { print(error) }


                }


      }

      @IBOutlet weak var StepCount: UILabel!



 }

1 个答案:

答案 0 :(得分:0)

您可以使用HKStatisticsQuery获取今天的步骤。您现在可以在视图控制器中使用getTodaysSteps方法并设置标签的文本属性。

Swift 3.1:

    let healthStore = HKHealthStore()

    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, error) in
            var resultCount = 0.0

            guard let result = result else {
                log.error("Failed to fetch steps = \(error?.localizedDescription ?? "N/A")")
                completion(resultCount)
                return
            }

            if let sum = result.sumQuantity() {
                resultCount = sum.doubleValue(for: HKUnit.count())
            }

            DispatchQueue.main.async {
                completion(resultCount)
            }
        }

        healthStore.execute(query)
    }

您可以这样调用此方法:

override func viewDidLoad() {
    super.viewDidLoad()

    getTodaysStepCount { [weak self] steps in
        self?.StepCount.text = "\(steps)"
    }
}