简体   繁体   English

如何从 HealthKit Swift 3 显示步数

[英]How to display steps count from HealthKit Swift 3

Hi i want to display on my app dayly step count from healthKit嗨,我想在我的应用程序上显示来自 healthKit 的每日步数
This is my code:这是我的代码:

imports进口

import UIKit
import HealthKit

Class instance类实例

var healthStore = HKHealthStore()

viewDidLoad method 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()

        })
    }

}

Write:写:

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

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

Read:阅读:

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

    return returnSet
}

Now I want to create func updateSteps()现在我想创建 func updateSteps()

I have an answer to my question我有我的问题的答案

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)
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM