简体   繁体   中英

Swift HealthKit UpdateQuery only getting called once

I'm currently working on a Project where I want to get the Heart Rate from Health Kit every time it changes. I tried already with a Timer too but the result is the same.

It gets called maximum 2 times and never changes the result again. Also anybody who has experience with Swift can tell me if I want to get the maximum pulse is HKStatisticsQuery is a good choice for it?

Finally here is my code I don't have a clue what I did wrong. Also I'm truly sorry for the amateur code I'm a beginner in making programs with Swift.

func createHeartRateStreamingQuery() -> HKQuery? {
    guard let heartRateType: HKQuantityType = HKQuantityType.quantityType(forIdentifier: .heartRate) else {
        return nil
    }
    let predicate = HKQuery.predicateForSamples(withStart: nil, end: nil,options: .strictEndDate)
    let heartRateQuery = HKAnchoredObjectQuery(type: heartRateType, predicate: predicate, anchor: nil, limit: HKObjectQueryNoLimit) { (query, sampleObjects, deletedObjects, newAnchor, error) in

        guard let newAnchor = newAnchor,
            let sampleObjects = sampleObjects else {
                return
        }
        self.anchor = newAnchor
        self.heartRateDelegate?.heartRateUpdated(heartRateSamples: sampleObjects)
    }
    heartRateQuery.updateHandler = {(query, sampleObjects, deletedObjects, newAnchor, error) -> Void in

        guard let newAnchor = newAnchor,
            let sampleObjects = sampleObjects else {
                return
        }
        self.anchor = newAnchor
        self.heartRateDelegate?.heartRateUpdated(heartRateSamples: sampleObjects)
    }
    return heartRateQuery
}

After researching I came to the conclusion that only using your iPhone never going to get you near real-time heart rate check and the updateHandler works perfectly fine. The iPhone's HealthKit database only updating after you exit and reenter your app or end of a workout session.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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