Приложение Apple Health предоставляет данные по дате, как показано на рисунке ниже.
Используя HealthKit
, я извлекаю данные о шагах из Apple Health, поскольку
let p1 = HKQuery.predicateForSamples(withStart: fromDate, end: Date(), options: .strictStartDate)
let p2 = HKQuery.predicateForObjects(withMetadataKey: HKMetadataKeyWasUserEntered, operatorType: .notEqualTo, value: true)
let timeSortDesriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)//as in health kit entry
let quantityType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!
let predicate = HKQuery.predicateForSamples(withStart: fromDate, end: Date(), options: .strictStartDate)
let sourceQuery = HKSourceQuery(sampleType: quantityType, samplePredicate: predicate, completionHandler: { query,sources,error in
if sources?.count != 0 && sources != nil {
let lastIndex = sources!.count - 1
var sourcesArray = Array(sources!)
for i in 0..
sourceQuery дает несколько таких объектов, как Apple, часы, мой iPhone. далее я использую цикл с HKSampleQuery
, который дает объект HKQuantitySample
. Проблема в [HKQuantitySample]
дает массив данных шага, который не отсортирован по дате. Я ищу данные, которые являются клубными на дату, например, что показывает здоровье яблока в приложении Health.
Да, есть обходной путь, такой как ручная сортировка данных из [HKQuantitySample]
по дате. но может быть обходной путь, используя predicates
или что-то еще. Пожалуйста, не стесняйтесь спрашивать, нужна ли вам дополнительная информация.
РЕДАКТИРОВАТЬ: В соответствии с предложением @Allan я добавил HKStatisticsCollectionQuery , ДА, он дает данные по дате , но получение количества шагов отличается от состояния здоровья Apple. Приложение. Что-то требуется добавить / изменить в приведенном ниже коде?
let last10Day = Calendar.current.date(byAdding: .day, value: -10, to: Date())!
var interval = DateComponents()
interval.day = 1
let quantityType1 = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!
// Create the query
let query = HKStatisticsCollectionQuery(quantityType: quantityType1,
quantitySamplePredicate: nil,
options: .cumulativeSum,
anchorDate: last10Day,
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: \(String(describing: error?.localizedDescription)) ***")
}
let endDate = Date()
statsCollection.enumerateStatistics(from: last10Day, to: endDate, with: { (statistics, stop) in
if let quantity = statistics.sumQuantity() {
let date = statistics.startDate
let value = quantity.doubleValue(for: HKUnit.count())
print("--value-->",value, ",--For Date-->",date)
}
})
}
healthStore.execute(query)