我在我的应用程序中使用health-kit来读取用户的步骤和活动。这一切都没问题但是我想只阅读自动检测到的活动和步骤。目前,我获得了人工进入的所有数据天气或健康应用程序自动检测到的数据。到目前为止,这是我的代码
func todaySteps(completion: (Double, NSError?) -> () )
{
let type = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount) // The type of data we are requesting
let date = NSDate()
print(date)
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let newDate = cal.startOfDayForDate(date)
print(newDate)
let predicate = HKQuery.predicateForSamplesWithStartDate(newDate, endDate: NSDate(), options: .None) // Our search predicate which will fetch all steps taken today
let query = HKSampleQuery(sampleType: type!, predicate: predicate, limit: 0, sortDescriptors: nil) { query, results, error in
var steps: Double = 0
if results?.count > 0
{
for result in results as! [HKQuantitySample]
{
steps += result.quantity.doubleValueForUnit(HKUnit.countUnit())
}
}
completion(steps, error)
}
executeQuery(query)
}
但在哪里以及如何检查用户输入或自动检测到的数据?我也看到了This问题,但它在目标c中,我无法完全理解它,所以请指导我。
答案 0 :(得分:0)
我自己解决了这个问题。这就是我做的方式。
func todaySteps(completion: (Double, NSError?) -> () )
{
let type = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)
let date = NSDate()
print(date)
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let newDate = cal.startOfDayForDate(date)
print(newDate)
let predicate = HKQuery.predicateForSamplesWithStartDate(newDate, endDate: NSDate(), options: .None)
let query = HKSampleQuery(sampleType: type!, predicate: predicate, limit: 0, sortDescriptors: nil) { query, results, error in
var steps: Double = 0
if results?.count > 0
{
for result in results as! [HKQuantitySample]
{
print("Steps \(result.quantity.doubleValueForUnit(HKUnit.countUnit()))")
// checking and truncating manually added steps
if result.metadata != nil {
// Theses steps were entered manually
}
else{
// adding steps to get total steps of the day
steps += result.quantity.doubleValueForUnit(HKUnit.countUnit())
}
}
}
completion(steps, error)
}
executeQuery(query)
}