HKAnchoredObjectQuery updateHandler只调用一次

时间:2015-12-07 21:33:21

标签: swift health-kit

我在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只在我使用Workout app时调用一次。

看起来像是同一个错误 - https://forums.developer.apple.com/thread/14571Monitor heart rate from HealthKit --> HKAnchoredObjectQuery only called after applicationDidBecomeActive (BUG or FEATURE?)

2 个答案:

答案 0 :(得分:1)

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

HKHealthStore.enableBackgroundDeliveryForType()

我在

之前执行此方法
HKHealthStore.executeQuery().

答案 1 :(得分:0)

更新:Swift 5

您可以指定 ObjectType 以及您希望它触发的频率。

HKHealthStore.enableBackgroundDelivery(for: HKObjectType, frequency: HKUpdateFrequency.immediate)