Stopping HealthKit observer queries
—
Tips
Apple documentation about Executing Observer Queries says that “To stop the query, call the HealthKit store’s stopQuery:
method.”.
That method takes the query you want to stop as a parameter. Which is ok if you have access to the query.
But what if you created the query in a previous run of the app, and it has been running happily in the background since?
You cannot persist the query, like you would do with an HKQueryAnchor
.
My solution was to persist the hash
value of the query and associate with it whether the query should be stopped or not. Then, in the updateHandler
of the query, I stop the query, if necessary. This is possible because the updateHandler
has the query as one of the parameters.
let query = HKObserverQuery(sampleType: sampleType, predicate: nil) { (query, completionHandler, errorOrNil) in
if let error = errorOrNil {
// Properly handle the error.
completionHandler()
return
}
// Check if query should be stopped.
if shouldStopQuery(queryHash: query.hash) {
HKHealthStore.stop(query)
completionHandler()
return
}
// Execute other queries to access the new data.
completionHandler()
}
Leave a comment