Stopping HealthKit observer queries
1 min read

Stopping HealthKit observer queries

How to stop a HealthKit observer query that has been running in the background.

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()
}

Wanna stay up-to-date with Flutter and Dart?

Subscribe to get a weekly email with the best articles about Flutter and Dart.

    We won't send you spam. Unsubscribe at any time.