ios - 如何读取healthKit心率数据?

标签 ios swift healthkit 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 }
    }
}

现在这是我的 View Controller 代码(我不确定为什么这不起作用):

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
}


}

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

此外 - 这些代码都不会用于家庭作业、个人/专业项目...等。它只是为了好玩/学习,大部分代码是我尝试过的以及我在多个堆栈溢出流和其他论坛中发现的。

最佳答案

您需要实际执行查询。

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

关于ios - 如何读取healthKit心率数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37229992/

相关文章:

ios - 获取传递给完成处理程序以进行单元测试的值

ios - HealthKit:HKObserverQuery不触发

ios - 检查是否已在 Apple Watch 上授予 HealthKit 权限的最佳方法?

python - Socketswift 连接到特定 IP 地址超时

ios - 在 Swift map 上的 MKOverlay 中添加模糊 View

iphone - ios Mapkit : fix annotation on middle of map

ios - 如何解决将应用程序上传到 ios 中的应用程序商店时出现的问题

iOS 9 删除 HealthKit 中的数据

iOS 无法在模拟器 Xcode 6.1(6A1052d) 中运行应用程序

objective-c - Linea pro 设备检测