简体   繁体   中英

WatchOS 4 not receiving heart rate samples?

Using Apple's sample code from SpeedySloth, I am getting heart rate samples on the simulator but not getting any samples on my Series 0 Apple Watch running WatchOS 4.1. Is this a bug? Anyone else having this issue?

code:

 func startHeartRateQuery(from startDate: Date, updateHandler: @escaping ([HKQuantitySample]) -> Void) {
        let typeIdentifier = HKQuantityTypeIdentifier.heartRate
        startQuery(ofType: typeIdentifier, from: startDate) { _, samples, _, _, error in
            guard let quantitySamples = samples as? [HKQuantitySample] else {
                print("Heart rate query failed with error: \(String(describing: error))")
                return
            }
            print("heartRate samples = \(quantitySamples)")
            updateHandler(quantitySamples)

        }
    }



    //Generic helper function 
    private func startQuery(ofType type: HKQuantityTypeIdentifier, from startDate: Date, handler: @escaping
        (HKAnchoredObjectQuery, [HKSample]?, [HKDeletedObject]?, HKQueryAnchor?, Error?) -> Void) {
        let datePredicate = HKQuery.predicateForSamples(withStart: startDate, end: nil, options: .strictStartDate)
        let devicePredicate = HKQuery.predicateForObjects(from: [HKDevice.local()])
        let queryPredicate = NSCompoundPredicate(andPredicateWithSubpredicates:[datePredicate, devicePredicate])

        let quantityType = HKObjectType.quantityType(forIdentifier: type)!

        let query = HKAnchoredObjectQuery(type: quantityType, predicate: queryPredicate, anchor: nil,
                                          limit: HKObjectQueryNoLimit, resultsHandler: handler)
        query.updateHandler = handler
        healthStore.execute(query)

        activeDataQueries.append(query)
    }

I had a similar issue that I've been troubleshooting for ages. Turns out for some reason, although updateHandler is set in the query, it isn't being triggered even though new samples are being added to HealthStore. I think it's an issue with the latest OS (4.2).

As an alternative, I've been polling HealthStore every 5 seconds using refreshed query anchors. It works as expected now. I have a state variable that's checked whether to continue polling or not.

I had the very same problem on the same Apple sample code. Having tried it with WatchOS 4.1 a few months ago, i can safely assume it's broken since 4.2.

However i was able to make it work by simply requesting the necessary HK authorizations to the health store. Just by overriding the initializer or HealthStoreManager.swift like so:

// HealthStoreManager.swift

override init() {
    super.init()
    let allTypes = Set([HKObjectType.workoutType(),
                        HKSeriesType.workoutRoute(),
                        HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)!,
                        HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)!])

    healthStore.requestAuthorization(toShare: allTypes, read: allTypes) { (success, error) in
        if !success {
            print(error?.localizedDescription ?? "")
        }
    }
}

Reinstall the app from scratch and it should now work properly.

I had several problems getting the SpeedySloth app to gather data. Took 4 days reading every SO post on the subject and trying everything I could think of. I ended up deleting all the old Xcode versions off my computer (I only have 9.2 installed now) and I also deleted all the simulator files in ~/Library/Logs/CoreSimulator/ and it ended up working. Weird.

I ended up upgrading my watch from a series 0 to a series 3, and I no longer have any problem getting heart rates on WatchOS 4.1. The problem may have been hardware related. Posting an update to show my code above is good for pulling heart rate data.

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