简体   繁体   中英

iOS HealthKit track user steps during session

I am trying to track user steps taken during a session. These sessions can be anywhere from 30 seconds to 30 minutes. I start the session and start walking around and then one minute later I stop the session. This always returns 0 steps. Here is the code I am running.

func readUserSteps(startDate:NSDate, endDate:NSDate) {

    let weightSampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)
    let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: .None)

    let query = HKSampleQuery(sampleType: weightSampleType!, predicate: predicate, limit: 0, sortDescriptors: nil, resultsHandler: {
        (query, results, error) in
        if results == nil {
            print("There was an error running the query: \(error)")
        } else {
            var stepCount:Double = 0
            for steps in results as! [HKQuantitySample]
            {
                stepCount += steps.quantity.doubleValueForUnit(HKUnit.countUnit())
            }
            print("Steps Taken: \(stepCount)")
        }
    })

    self.healthKitStore.executeQuery(query)
}

I save the current date as so: let startTime = NSDate() to represent the start of a session and once the user stops the session I save the end of the session as so: let endTime = NSDate() . I then call the function above with these two variables created. Unfortunately, 'stepCount' is always returning 0..what am I doing wrong here?

If you are only interested in counting the user's steps as recorded by their iPhone or Apple Watch, I suggest using the CMPedometer API instead as it will always have the most up-to-date records. If you'd still like to use HealthKit, though, you will need to indicate to HealthKit that your app is interested in "observing" steps by executing any of the query types that has an updateHandler property ( HKObserverQuery , HKStatisticsCollectionQuery , or HKAnchoredObjectQuery ). Execute one of those queries with an update handler at the beginning of the session to get HealthKit to import step counts more frequently.

HKObserverQuery will simply notify you when there are new step counts in HealthKit, so at the end of the session you'll need to re-query for the total. On the other hand, HKStatisticsCollectionQuery and HKAnchoredObjectQuery can stream results to your app while the session is running which could be better for performance.

Finally, be careful about simply summing the values of HKQuantitySamples to compute the total step count. HealthKit data from multiple sources can overlap in time. For instance, an Apple Watch user could have multiple sources of steps in HealthKit for the periods of the day when they were both wearing their watch and carrying their phone. For this reason, it's better to use HKStatisticsQuery or HKStatisticsCollectionQuery to compute a sum, since it avoids double counting overlapping samples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM