简体   繁体   English

Swift - Healthkit 的 HKSampleQuery 示例

[英]Swift - HKSampleQuery Samples of Healthkit

I'm trying to return the last 7 days samples of heartbeat recorded.我正在尝试返回最近 7 天记录的心跳样本。 I think i'm on the good way but i'm still not quite sure about my query part.我认为我的方式很好,但我仍然不太确定我的查询部分。 Here's what I've done so far.这是我到目前为止所做的。 The only think that is getting printed is唯一被打印出来的想法是

95 count/min 90EBAB07-9CAB-445E-A967-4BD5E8AADAA4 "User’s Apple Watch" (5.1.3), "Watch3,2" (5.1.3)"Apple Watch" metadata: {
    HKMetadataKeyHeartRateMotionContext = 0;
} (2019-02-22 21:51:31 -0400 - 2019-02-22 21:51:31 -0400)

here's my query:这是我的查询:

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

        let sortDescriptor = NSSortDescriptor(
            key: HKSampleSortIdentifierEndDate,
            ascending: false)

        let heartRateType = HKSampleType.quantityType(forIdentifier: .heartRate)!
        let endDate = Date()
        let startDate = endDate.addingTimeInterval(-1.0 * 60 * 60 * 24)
        let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: [])

        let query = HKSampleQuery(sampleType: heartRateType, predicate: predicate, limit: 0, sortDescriptors: [sortDescriptor])
        { (query, result, error) -> Void in
        DispatchQueue.main.async {
        guard let result = result,
            let resultCount = result.first as? HKQuantitySample else {
            print("Failed to fetch heart rate")
            return
            }
            completion(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)"
            }
    }

This should return you the last 7 days.这应该会返回您过去 7 天的信息。 Hope it help!希望有帮助!

let startDate = Date() - 7 * 24 * 60 * 60
let endDate = Date()
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: [])

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

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