Contenu connexe
Similaire à HealthKitで日別のデータを一度に取得する (6)
HealthKitで日別のデータを一度に取得する
- 9. https://github.com/yimajo/
HealthKitStatisticsCollectionDemo
func requestWeakStatisticsCollection() {
// 今から一週間前
let calendar: NSCalendar = NSCalendar.currentCalendar()
let day = -7
let now = NSDate()
let today = calendar.startOfDayForDate(now)
// endは今でいい
let endDate = now
// startはdayを今日から加算した
let startDate = calendar.dateByAddingUnit([.Day], value: day, toDate: today, options: NSCalendarOptions.WrapComponents)!
// 今日の始まりの0時からアンカーにしたい
let anchorDate = today
let intervalComponents = NSDateComponents()
intervalComponents.day = 1
let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: [.None])
let quantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)!
let statsOptions: HKStatisticsOptions = [HKStatisticsOptions.SeparateBySource, HKStatisticsOptions.CumulativeSum]
let query = HKStatisticsCollectionQuery(quantityType: quantityType, quantitySamplePredicate: predicate, options: statsOptions,
anchorDate: anchorDate, intervalComponents: intervalComponents)
query.initialResultsHandler = { [unowned self] (query, result, error) in
guard let result = result where error == nil else{
return
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.statisticsCollection = result
self.tableView.reloadData()
})
}
healthStore.executeQuery(query)
}