如何阅读healthKit Heartrate数据?

时间:2016-05-14 17:49:19

标签: ios swift health-kit health-monitoring

我知道这些问题已被提出,但尚未得到回答。我从这样的线程中尝试了一些东西: Heart Rate With Apple's Healthkit

我尝试将其从Objective-C转换为Swift但是没有用。

我的问题是,从健康套件中读取心率数据的最佳方法是什么。我希望能够从开始拍摄时读取每个心率测量值,并且我希望能够看到所述测量值的时间/日期标记。

我在这里要求许可:

import Foundation
import UIKit
import HealthKit

class HealthKitManager: NSObject {

static let healthKitStore = HKHealthStore()

static func authorizeHealthKit() {

    let healthKitTypes: Set = [
        HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!,
    ]

    healthKitStore.requestAuthorizationToShareTypes(healthKitTypes,
                                                    readTypes: healthKitTypes) { _, _ in }
    }
}

这是我现在的视图控制器代码(我不确定为什么这不起作用):

import UIKit
import HealthKit

class ViewController: UIViewController {

let health: HKHealthStore = HKHealthStore()
let heartRateUnit:HKUnit = HKUnit(fromString: "count/min")
let heartRateType:HKQuantityType   = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!
var heartRateQuery:HKQuery?


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

     @IBAction func authorizeTapped(sender: AnyObject) {
    print("button tapped")
    self.createStreamingQuery()
    HealthKitManager.authorizeHealthKit()

}


func createStreamingQuery() -> HKQuery
{
    let queryPredicate  = HKQuery.predicateForSamplesWithStartDate(NSDate(), endDate: nil, options: .None)

    let query:HKAnchoredObjectQuery = HKAnchoredObjectQuery(type: self.heartRateType, predicate: queryPredicate, anchor: nil, limit: Int(HKObjectQueryNoLimit))
    { (query:HKAnchoredObjectQuery, samples:[HKSample]?, deletedObjects:[HKDeletedObject]?, anchor:HKQueryAnchor?, error:NSError?) -> Void in

        if let errorFound:NSError = error
        {
            print("query error: \(errorFound.localizedDescription)")
        }
        else
        {
            //printing heart rate
            if let samples = samples as? [HKQuantitySample]
            {
                if let quantity = samples.last?.quantity
                {
                    print("\(quantity.doubleValueForUnit(self.heartRateUnit))")
                }
            }
        }
    }

    query.updateHandler =
        { (query:HKAnchoredObjectQuery, samples:[HKSample]?, deletedObjects:[HKDeletedObject]?, anchor:HKQueryAnchor?, error:NSError?) -> Void in

            if let errorFound:NSError = error
            {
                print("query-handler error : \(errorFound.localizedDescription)")
            }
            else
            {
                //printing heart rate
                if let samples = samples as? [HKQuantitySample]
                {
                    if let quantity = samples.last?.quantity
                    {
                        print("\(quantity.doubleValueForUnit(self.heartRateUnit))")
                    }
                }
            }//eo-non_error
    }//eo-query-handler

    return query
}


}

我无法在控制台上打印任何内容,这正是我想要的。

此外 - 这些代码都没有用于家庭作业,个人/专业项目......等等。它只是为了好玩/学习,而且大部分代码都是我尝试过的,也是我通过多个堆栈流程和其他论坛找到的。

1 个答案:

答案 0 :(得分:0)

您需要实际执行查询。

let query = self.createStreamingQuery()
self.health.executeQuery(query)