artyom - 10 months ago 67

iOS Question

I need to create statistics for month of HKQuantityType with Cumulative aggregation style, like in Health App on year view.

HKStatisticsCollectionQuery can calculate only sum for Cumulative types.

How it works now.

I'm making 12 HKSampleQueries. Each quest has predicate with start and end dates of a month.

Then I'm iterating over each query result to calculate number of days that has samples (One day can contain more then one sample).

After number of days ready I'm divide sum of moths on number of days.

Main problem is that if I get all samples in a moth, I got about 10000 samples.

Number of month is 12 so it's about 120000 samples for the one Metric in a year.

I'm running it in a background threads but amount of memory is about 180mb while calculating average for each month and it takes about a minute to calculate.

Is there any possibilities to get number of samples in a month, groped by day?

I didn't found any solution for it :(

Answer

Try `HKStatisticsCollectionQuery`

with an interval of one day. You can then average the sums per day that are returned. It should be orders of magnitude more efficient than querying for all the samples in each month (and more correct since you would need to account for overlapping samples returned by `HKSampleQuery`

).