gpt4 book ai didi

ios - 查询 HealthKit 以获取当天的总步数

转载 作者:行者123 更新时间:2023-11-29 11:52:22 29 4
gpt4 key购买 nike

我正在调用一个函数,并且一直在尝试弄清楚如何更新我的应用程序以反射(reflect)当天的总步数。目前,我的代码只提供了最近记录的步数。我在理解如何使用 HKStatisticsQuery 时遇到了问题,但这是我目前拥有的功能,可以提供最新的结果。

-(void)updateStepsLabel{
// Query to get the user's latest steps, if it exists.
HKQuantityType *stepsType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

[_healthStore aapl_mostRecentQuantitySampleOfType:stepsType predicate:nil completion:^(HKQuantity *mostRecentQuantity, NSError *error) {
if (!mostRecentQuantity) {
NSLog(@"Either an error occured fetching the user's steps information or none has been stored yet. In your app, try to handle this gracefully.");

dispatch_async(dispatch_get_main_queue(), ^{
self.todaysStepValueLabel.text = NSLocalizedString(@"Not available", nil);
});
}
else {
// Determine the steps in the required unit.
HKUnit *stepUnit = [HKUnit countUnit];
double usersWeight = [mostRecentQuantity doubleValueForUnit:stepUnit];

// Update the user interface.
dispatch_async(dispatch_get_main_queue(), ^{
self.todaysStepValueLabel.text = [NSNumberFormatter localizedStringFromNumber:@(usersWeight) numberStyle:NSNumberFormatterNoStyle];
self.todaysStepValueLabel.textColor = [UIColor blackColor];
self.todaysStepValueLabel.font = [UIFont systemFontOfSize:25];


});
}
}];

}

最佳答案

这里贴出一个Swift代码的答案,希望你能转成Obj-c

我在类中写了下面的函数,定义如下

class MyHealthStore: HKHealthStore { }

.

func TodayTotalSteps(completion: (stepRetrieved: Double) -> Void) {

let type = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount) // The type of data we are requesting

let calendar = NSCalendar.currentCalendar()
let interval = NSDateComponents()
interval.day = 1

let anchorComponents = calendar.components([.Day , .Month , .Year], fromDate: NSDate())
anchorComponents.hour = 0
let anchorDate = calendar.dateFromComponents(anchorComponents)

let stepsQuery = HKStatisticsCollectionQuery(quantityType: type!, quantitySamplePredicate: nil, options: .CumulativeSum, anchorDate: anchorDate!, intervalComponents: interval)

stepsQuery.initialResultsHandler = {query, results, error in
let endDate = NSDate()

var totalSteps = 0.0
let startDate = calendar.dateByAddingUnit(.Day, value: 0, toDate: endDate, options: [])
if let myResults = results{ myResults.enumerateStatisticsFromDate(startDate!, toDate: endDate) { statistics, stop in
if let quantity = statistics.sumQuantity(){
//let date = statistics.startDate
totalSteps = quantity.doubleValueForUnit(HKUnit.countUnit())
// print("\(date): steps = \(steps)")
}
self.todayManuallyAddedSteps({ (manuallSteps, error) in
if error != nil {
print(error)
} else {
totalSteps = totalSteps - manuallSteps
completion(stepRetrieved: totalSteps)
return
}
})
//completion(stepRetrieved: totalSteps)

}
} else {
// mostly not executed
completion(stepRetrieved: totalSteps)
}
}
executeQuery(stepsQuery)
}

如果您想截断手动添加的步骤,请使用此功能

func todayManuallyAddedSteps(completion: (Double, NSError?) -> () )
{
let type = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount) // The type of data we are requesting

let date = NSDate()
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let newDate = cal.startOfDayForDate(date)
let predicate = HKQuery.predicateForSamplesWithStartDate(newDate, endDate: NSDate(), options: .None) // Our search predicate which will fetch all steps taken today

// The actual HealthKit Query which will fetch all of the steps and add them up for us.

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]
{
// checking and adding manually added steps
if result.sourceRevision.source.name == "Health" {
// these are manually added steps

steps += result.quantity.doubleValueForUnit(HKUnit.countUnit())
}
else{
// these are auto detected steps which we do not want from HKSampleQuery
}
}
completion(steps, error)

return
} else {
// mostly not executed
completion(steps, error)
}
}
executeQuery(query)
}

下面是如何调用它

 MyHealthStore.sharedHealthStore.TodayTotalSteps { (stepRetrieved) in 
print(stepRetrieved)
}

希望对您有所帮助,如果您发现任何困难,请告诉我。

关于ios - 查询 HealthKit 以获取当天的总步数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40626138/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com