[英]Get the latest (most recent) Step value from HealthKit (HKStatistics)
我想獲取Health(Kit)App條目的最后一個(又是最近的)值。 例如,最新的HKSource條目中的步進值。
我認為可以在查詢建築物中使用HKStatisticsOptions.discreteMostRecent
屬性。
當前結果
該代碼工作正常,沒有錯誤。 我的統計信息具有正確的開始和結束日期(如果只有一個值可用,則開始和結束日期相同)。
問題在於, statistics.sources
列表始終為nil,就像statistics.mostRecentQuantity()
也返回nil一樣。
所有與sumQuantity()
不相關的總和運算sumQuantity()
正常工作。
其他Stackoverflow帖子
我會嘗試使用限制為1的查詢和本文中的排序描述來實現這一想法,但我也需要在詳細信息視圖中顯示其他歷史值。 這就是為什么我認為我可以只請求數量的日期框架,將最新的作為我的“最后一個”,而將其他所有作為我的歷史記錄表視圖。
碼
func requestMeasurements(completion: @escaping (HKStatistics?, AppError?) -> Void)
{
let healthStore = HKHealthStore()
// Check if HK is available.
guard HKHealthStore.isHealthDataAvailable() else
{
completion(nil, AppError.healthInformationNotAvailable)
return
}
// Check if HK information is available
guard let quantitiyType = HKQuantityType.quantityType(forIdentifier: .stepCount) else
{
completion(nil, AppError.requestedHealthDataTypeNotAvailable)
return
}
let typeSet: Set = [quantitiyType]
// Request user access to HK and especially this type
healthStore.requestAuthorization(toShare: nil, read: typeSet)
{ success, error in
// Ensure that the app has the required access
if success == false
{
print(error?.localizedDescription ?? "<no error description>")
completion(nil, AppError.noAccessToRequestedInformation)
return
}
// Build query
let now = Date()
let lastSync = Calendar.current.startOfDay(for: now)
let prediction = HKQuery.predicateForSamples(withStart: lastSync, end: now, options: .strictStartDate)
let query = HKStatisticsQuery(quantityType: quantitiyType, quantitySamplePredicate: prediction, options: HKStatisticsOptions.discreteMostRecent)
{ _, statistics, error in
// Check for error.
if let _error = error
{
print("An error occured: \(_error.localizedDescription)")
completion(nil, AppError.requestingFailed)
return
}
// Check if statistics are available.
guard let _statistics = statistics else
{
completion(nil, AppError.requestingFailed)
return
}
completion(_statistics, nil)
}
// Execure query
healthStore.execute(query)
}
如果您只想使用數量,等等。只需使用HKSampleQuery
而不是HKStatisticsQuery
。
之后,您只需HKSample
的結果列表HKSample
為[HKQuantitySample]
。
現在您有了開始和結束日期,還有quantity
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.