HKObserverQuery无法在iPhone

时间:2016-04-10 10:56:12

标签: ios iphone swift health-kit hkobserverquery

我想立即从Apple手表收集心率数据到iPhone,但即使我按照Apple's document,我发现无法创建和更新HKAnchorObjectQuery(在HKObserverQuery中)。

此外,HKObserverQuery仅在开始执行应用程序时才有效。

我已经试了两个星期,再也没有想法......

以下代码:

func createHeartRateStreamingQuery(workoutStartDate: NSDate) -> HKQuery?{

            let sampleType =  HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!


            let query = HKObserverQuery(sampleType: sampleType, predicate: nil) {
                query, completionHandler, error in

                if error != nil {
                    // Perform Proper Error Handling Here...
                    print("*** An error occurred while setting up the observer. ***")
                    abort()
                }else{
                    print("sampleType initiated: ",sampleType)
                }

                let anchoredQuery = HKAnchoredObjectQuery(type: sampleType, predicate: nil, anchor: self.anchor, limit: Int(HKObjectQueryNoLimit)) { (query1, sampleObjects, deletedObjects, newAnchor, error) -> Void in
                print("anchored query initiated!")
                guard let newAnchor = newAnchor
                    else {return}
                self.anchor = newAnchor
                self.updateHeartRate(sampleObjects) //use to display the heart rate data
            }

                anchoredQuery.updateHandler = {(query1, samples, deleteObjects, newAnchor, error) -> Void in
                    self.anchor = newAnchor!
                    self.updateHeartRate(samples) //use to display the heart rate data
                    print("anchored query updating!")
                }

                completionHandler()
            }

            return query
        }

     let query = createHeartRateStreamingQuery()
     healthStore.executeQuery(query)

寻找你的回复!

Here's我的另一个问题与此相关。

1 个答案:

答案 0 :(得分:0)

您不能在HKObserverQuery中使用HKSampleQuery。 HKObserverQuery的updateHandler。观察者查询的处理程序可以在后台模式下执行,但其中一个示例查询无法在后台模式下执行。