Apple 健康应用程序按日期提供数据,如下图所示。
通过使用HealthKit
我从苹果健康获取步骤数据作为
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 watch、My iPhone。此外,我正在使用 for 循环HKSampleQuery
来给出HKQuantitySample
对象。问题是[HKQuantitySample]
给出了未按日期排序的步骤数据数组。我正在寻找日期俱乐部的数据,例如健康应用程序中的苹果健康显示。
是的,有一种解决方法,例如[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)