从HealthKit查询心率值使应用程序崩溃

时间:2019-02-22 18:38:55

标签: ios swift health-kit

每当我按下按钮时,我都试图将我的心率显示为标签。我还希望能够在打印心率时选择一个特定的日期,我希望能够通过电子邮件通过电子邮件发送该特定的频率。但是我的主要问题是,每当我单击按钮时,我都会不断收到“线程1:信号SIGABRT”。一切似乎都按预期链接。

import UIKit
import HealthKit

class ViewController: UIViewController {
let healthStore = HKHealthStore()

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

@IBAction func authoriseHealthKitAccess(_ sender: Any) {
    let healthKitTypes: Set = [

        HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!
    ]
    healthStore.requestAuthorization(toShare: healthKitTypes, read: healthKitTypes) { (_, _) in
        print("Authorising")
    }
    healthStore.requestAuthorization(toShare: healthKitTypes, read: healthKitTypes) { (bool, error) in
        if let e = error {
            print("oops something went wrong during authorisation \(e.localizedDescription)")
        } else {
            print("User has completed the authorization process")
        }
    }
}

func getTodaysHeartRate(completion: @escaping (Double) -> Void) {

    let heartRateType = HKQuantityType.quantityType(forIdentifier: .heartRate)!

    let now = Date()
    let startOfDay = Calendar.current.startOfDay(for: now)
    let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)

    let query = HKStatisticsQuery(quantityType: heartRateType, quantitySamplePredicate: predicate, options: .cumulativeSum) { (_, result, error) in
        var resultCount = 0
        guard let result = result else {
            print("Failed to fetch heart rate")
            completion(Double(resultCount))
            return
        }
        if let sum = result.sumQuantity() {
            resultCount = Int(sum.doubleValue(for: HKUnit.count()))
        }

        DispatchQueue.main.async {
            completion(Double(resultCount))
        }
    }
    healthStore.execute(query)
}

@IBOutlet weak var heartRate: UILabel!
@IBAction func getHeartRate(_ sender: Any) {
    getTodaysHeartRate { (result) in
        print("\(result)")
        DispatchQueue.main.async {
            self.heartRate.text = "\(result)"
        }
}
}

}
  

崩溃控制台:   2019-02-22 14:29:28.314380-0400   HeartRateSample [16416:2767191] *正在终止应用程序   捕获未捕获的异常“ NSInvalidArgumentException”,   原因:“统计信息”选项   HKStatisticsOptionCumulativeSum与离散数据类型HKQuantityTypeIdentifierHeartRate'不兼容   * 第一个抛出调用堆栈:(0x213d51ea4 0x212f21a50 0x213c58484 0x2265cf760 0x226575d60 0x22657e298 0x1035e4dc8 0x1035f382c   0x22657dcb0 0x226534bd4 0x102749ebc 0x10274a8dc 0x10274ae3c   0x24103e314 0x240acbd54 0x240acc074 0x240acb074 0x241077a6c   0x241078cd0 0x241057fcc 0x241126e38 0x241129830 0x241122320   0x213ce20e0 0x213ce2060 0x213ce1944 0x213cdc810 0x213cdc0e0   0x215f55584 0x24103cc00 0x10274d138 0x21379abb4)libc ++ abi.dylib:   以NSException(lldb)类型的未捕获异常终止

1 个答案:

答案 0 :(得分:3)

您处在正确的轨道上。您遇到的错误很简单。心率是一个离散选项,与统计选项“累积和”不兼容。

来自文档:

  

您不能将离散选项与累积选项结合使用。

Click here to learn more about HKStatisticsOptions

解决方案:

您需要使用.discreteMostRecent而不是 .cumulativeSum

更新的代码以适应必要的更改:

@available(iOS 12.0, *)
    func getTodaysHeartRate(completion: @escaping (Double) -> Void) {
        let heartRateType = HKQuantityType.quantityType(forIdentifier: .heartRate)!
        let now = Date()
        let startOfDay = Calendar.current.startOfDay(for: now)
        let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)

    // replaced options parameter .cumulativeSum with .discreteMostRecent
    let query = HKStatisticsQuery(quantityType: heartRateType, quantitySamplePredicate: predicate, options: .discreteMostRecent) { (_, result, error) in
        var resultCount = 0
        guard let result = result else {
            print("Failed to fetch heart rate")
            completion(Double(resultCount))
            return
        }

        // More changes here in order to get bpm value
        guard let beatsPerMinute: Double = result.mostRecentQuantity()?.doubleValue(for: HKUnit.count().unitDivided(by: HKUnit.minute())) else { return }
        resultCount = Int(beatsPerMinute)

        DispatchQueue.main.async {
            completion(Double(resultCount))
        }
    }
    healthStore.execute(query)
}

注意: .discreteMostRecent选项仅在iOS 12或更高版本上可用。