Я хочу получить все данные о сне из аптечки, Apple предлагает запрос HKStatisticsCollectionQuery для создания запроса типа коллекции, но я пробовал приведенный ниже код для шага, шаг пешком работает нормально, но когда я использую тот же код для снавремя сбора, тип количества не подтверждает приходящую ошибку, потому что сон - это категория, а не количество.
Как я могу получить данные сна за указанный период?Я могу получить данные о сне определенной даты, но не могу получить данные о сне.
let calendar = NSCalendar.currentCalendar()
let interval = NSDateComponents()
interval.day = 7
// Set the anchor date to Monday at 3:00 a.m.
let anchorComponents = calendar.components([.Day, .Month, .Year, .Weekday],
fromDate: NSDate())
let offset = (7 + anchorComponents.weekday - 2) % 7
anchorComponents.day -= offset
anchorComponents.hour = 3
guard let anchorDate = calendar.dateFromComponents(anchorComponents) else {
fatalError("*** unable to create a valid date from the given components ***")
}
guard let quantityType =
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount) else
{
fatalError("*** Unable to create a step count type ***")
}
// Create the query
let query = HKStatisticsCollectionQuery(quantityType: quantityType,
quantitySamplePredicate: nil,
options: .CumulativeSum,
anchorDate: anchorDate,
intervalComponents: interval)
// Set the results handler
query.initialResultsHandler = {
query, results, error in
guard let statsCollection = results else {
// Perform proper error handling here
fatalError("*** An error occurred while calculating the statistics: \(error?.localizedDescription) ***")
}
let endDate = NSDate()
guard let startDate = calendar.dateByAddingUnit(.Month, value: -3, toDate: endDate, options: []) else {
fatalError("*** Unable to calculate the start date ***")
}
// Plot the weekly step counts over the past 3 months
statsCollection.enumerateStatisticsFromDate(startDate, toDate: endDate) { [unowned self] statistics, stop in
if let quantity = statistics.sumQuantity() {
let date = statistics.startDate
let value = quantity.doubleValueForUnit(HKUnit.countUnit())
// Call a custom method to plot each data point.
self.plotWeeklyStepCount(value, forDate: date)
}
}
}
healthStore.executeQuery(query)
Я взял указанный выше код от этой ссылки на док-станцию для яблок .