我在iPhone应用程序中有ViewController

class ViewController: UIViewController {
    private let healthStore = HKHealthStore()
    private let heartRateUnit = HKUnit(fromString: "count/min")
    private var anchor = HKQueryAnchor(fromValue: Int(HKAnchoredObjectQueryNoAnchor))

    override func viewDidLoad() {
        super.viewDidLoad()

        if let query = createHeartRateStreamingQuery(NSDate()) {
            healthStore.executeQuery(query)
        }
    }

     func createHeartRateStreamingQuery(workoutStartDate: NSDate) -> HKQuery? {
        guard let quantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) else { return .None }

        let heartRateQuery = HKAnchoredObjectQuery(type: quantityType, predicate: nil, anchor: anchor, limit: Int(HKObjectQueryNoLimit)) { (query, sampleObjects, deletedObjects, newAnchor, error)  in }

        heartRateQuery.updateHandler = {(query, samples, deleteObjects, newAnchor, error) in
            self.updateHeartRate(samples)
        }

        return heartRateQuery
    }

但是在我使用健身应用程序时,heartRateQuery.updateHandler只会打一次电话。
看起来是同样的错误-https://forums.developer.apple.com/thread/14571Monitor heart rate from HealthKit --> HKAnchoredObjectQuery only called after applicationDidBecomeActive (BUG or FEATURE?)

最佳答案

您需要为您的样本类型(心率)启用后台传送。查找方法

HKHealthStore.enableBackgroundDeliveryForType()

我在
HKHealthStore.executeQuery().

09-03 23:54