如何显示HealthKit Swift 3中的步数

时间:2017-08-26 17:20:13

标签: ios swift health-kit hkhealthstore

您好我想在我的应用程序中显示来自healthKit的每日步数 这是我的代码:

进口

import UIKit
import HealthKit

类实例

var healthStore = HKHealthStore()

viewDidLoad方法

override func viewDidLoad() {
    super.viewDidLoad()

    if HKHealthStore.isHealthDataAvailable(){
        let writeDataTypes = dataTypesToWrite()
        let readDataTypes = dataTypesToWrite()

        healthStore.requestAuthorization(toShare: writeDataTypes as? Set<HKSampleType>, read: readDataTypes as? Set<HKObjectType>, completion: { (success, error) in
            if(!success){
                print("error")

                return
            }

            self.updateSteps()

        })
    }

}

写:

func dataTypesToWrite() -> NSSet{
    let stepsCount = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)

    let returnSet = NSSet(objects: stepsCount!)
    return returnSet
}

读:

func dataTypesToRead() -> NSSet{
    let stepsCount = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)
    let returnSet = NSSet(objects: stepsCount!)

    return returnSet
}

现在我要创建func updateSteps()

1 个答案:

答案 0 :(得分:2)

我对我的问题有答案

func updateSteps(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 {
                print("\(String(describing: error?.localizedDescription)) ")
                completion(resultCount)
                return
            }

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

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

        healthStore.execute(query)
    }