Как получить данные о здоровье Apple по дате? - PullRequest
0 голосов
/ 31 мая 2018

Приложение Apple Health предоставляет данные по дате, как показано на рисунке ниже.

enter image description here

При использовании 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..<sourcesArray.count {
                    let sourcePredicate = HKQuery.predicateForObjects(from: sourcesArray[i])
                    let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [p1, p2,sourcePredicate])
                    let query = HKSampleQuery(sampleType: quantityType, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: [timeSortDesriptor], resultsHandler: { query, results, error in
                        guard let samples = results as? [HKQuantitySample] else {
                            return
                        }......

sourceQuery дает несколько объектов, таких как часы Apple, Мой iPhone.далее я использую для цикла с HKSampleQuery, который дает HKQuantitySample объект.Проблема в [HKQuantitySample] дает массив данных шага, который не отсортирован по дате.Я ищу данные, которые являются клубными для даты, например, что показывает здоровье яблока в приложении Health.

Да, есть обходной путь, например, сортировка данных вручную из [HKQuantitySample] по дате.но может быть обходной путь, используя predicates или что-то еще.Пожалуйста, не стесняйтесь спрашивать, нужна ли вам какая-либо дополнительная информация.

РЕДАКТИРОВАТЬ: В соответствии с предложением @ Allan Я добавил HKStatisticsCollectionQuery , ДА, он предоставляет данные на дату но количество шагов не совпадает с полученным в приложении Apple Health.Что-то требуется добавить / изменить в приведенном ниже коде?

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)

Ответы [ 2 ]

0 голосов
/ 15 июня 2018

Используйте HKStatisticsCollectionQuery для извлечения данных за определенный период.Вот пример, показывающий, как получить шаги за последние 30 дней:

private let healthStore = HKHealthStore()
private let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!

func importStepsHistory() {
    let now = Date()
    let startDate = Calendar.current.date(byAdding: .day, value: -30, to: now)!

    var interval = DateComponents()
    interval.day = 1

    var anchorComponents = Calendar.current.dateComponents([.day, .month, .year], from: now)
    anchorComponents.hour = 0
    let anchorDate = Calendar.current.date(from: anchorComponents)!

    let query = HKStatisticsCollectionQuery(quantityType: stepsQuantityType,
                                        quantitySamplePredicate: nil,
                                        options: [.cumulativeSum],
                                        anchorDate: anchorDate,
                                        intervalComponents: interval)
    query.initialResultsHandler = { _, results, error in
        guard let results = results else {
            log.error("Error returned form resultHandler = \(String(describing: error?.localizedDescription))")
            return
    }

        results.enumerateStatistics(from: startDate, to: now) { statistics, _ in
            if let sum = statistics.sumQuantity() {
                let steps = sum.doubleValue(for: HKUnit.count())
                print("Amount of steps: \(steps), date: \(statistics.startDate)")
            }
        }
    }

    healthStore.execute(query)
}
0 голосов
/ 31 мая 2018

Если вы хотите, чтобы итоговые значения для количества шагов были разделены по дням, как в приложении Health, вы должны использовать HKStatisticsCollectionQuery, а не HKSampleQuery.Документация содержит пример кода для группировки результатов по неделям, но вы можете вместо этого изменить его по дням.

...