显示使用swift保存在Healthkit中的最后一个心率

时间:2016-12-15 08:21:46

标签: ios swift xcode health-kit hkhealthstore

我正在使用Swift为IOS应用程序构建应用程序。我只想显示Healthkit最后保存的心率。有人可以帮助我吗?

我的授权请求:

static func authorizeHealthKit() {

let HeartRateData: Set = [
    HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!,
    ]
HealthStore.requestAuthorization(toShare: HeartRateData, read: HeartRateData) {_,_ in }

}

    @IBAction func authorizeTapped(_ sender: AnyObject) {
        HeartrateViewController.authorizeHealthKit()
    }

获得心率:

func fetchHeartRateWithCompletionHandler (_ completionHandler: @escaping (Double?, NSError?)-> ()) {

    let now = Date()
    let startDate = now
    let endDate = now

let HeartRateSampleType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictStartDate)

let HeartRate = HKStatisticsQuery(quantityType: HeartRateSampleType!, quantitySamplePredicate: predicate, options: .cumulativeSum)
{ query, result, error in
    if result != nil {
        completionHandler(nil, error as NSError?)
        return
    }

    var HeartRateData = 0.0

    if let quantitiy = result!.sumQuantity() {
        let heartRateUnit = HKUnit(from: "count/min")
        HeartRateData = quantitiy.doubleValue(for: heartRateUnit)
    }

    completionHandler(HeartRateData, error as NSError?)

    }
    HeartRateTextField.text = String (describing: HeartRate)



}

但它不会在心率文本字段中显示任何内容。

1 个答案:

答案 0 :(得分:0)

您正在执行查询吗?

此外,您正在创建的查询效率不高。 您的开始日期和结束日期是相同的,谓词将不会在它们之间找到heartRate示例。 如果您正在寻找最新的心率样本,请阅读anchoredObjectQuery。