How to get cycling duration from HealthKit for ios app using Swift
Use given below function. It give you leatest 7 record. According to your requirement you can also change it.
func getHealthDataValue ( HealthQuantityType : HKQuantityType , strUnitType : String , GetBackFinalhealthData: ((( healthValues : [AnyObject] ) -> Void)!) )
{
if let heartRateType = HKQuantityType.quantityTypeForIdentifier(HealthQuantityType.identifier)
{
if (HKHealthStore.isHealthDataAvailable() ){
let sortByTime = NSSortDescriptor(key:HKSampleSortIdentifierEndDate, ascending:false)
// let timeFormatter = NSDateFormatter()
// timeFormatter.dateFormat = "hh:mm:ss"
//yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let query = HKSampleQuery(sampleType:heartRateType, predicate:nil, limit:7, sortDescriptors:[sortByTime], resultsHandler:{(query, results, error) in
guard let results = results else {
//include the healthkit error in log
if let errorDescription = error!.description as String?
{
GetBackFinalhealthData (healthValues: ["nodata"])
}
return
}
var arrHealthValues = [AnyObject]()
for quantitySample in results {
let quantity = (quantitySample as! HKQuantitySample).quantity
let healthDataUnit : HKUnit
if (strUnitType.length > 0 ){
healthDataUnit = HKUnit(fromString: strUnitType)
}else{
healthDataUnit = HKUnit.countUnit()
}
let tempActualhealthData = "\(quantity.doubleValueForUnit(healthDataUnit))"
let tempActualRecordedDate = "\(dateFormatter.stringFromDate(quantitySample.startDate))"
if (tempActualhealthData.length > 0){
let dicHealth : [String:AnyObject] = [HealthValue.kIdentifierValue :tempActualhealthData , HealthValue.kRecordDate :tempActualRecordedDate , HealthValue.kIdentifierDisplayUnit : strUnitType ]
arrHealthValues.append(dicHealth)
}
}
if (arrHealthValues.count > 0)
{
GetBackFinalhealthData (healthValues: arrHealthValues)
}
else
{
GetBackFinalhealthData (healthValues: [HealthValue.kNoData])
}
})
(self.HealthStore as! HKHealthStore).executeQuery(query)
}
}
}
Use above function as follow.
Here you need to pass a type and unit.
self.getHealthDataValue(HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodPressureDiastolic), strUnitType: "mmHg"
) { (arrHealth) -> Void in
}
HealthKit Swift getting today's steps
Here is the right way using HKStatisticsCollectionQuery courtesy of the direction from the code above.
This is written in Swift 3 so you may have to convert some of the code back to 2.3 or 2 if not on 3 yet.
Swift 3
func retrieveStepCount(completion: (stepRetrieved: Double) -> Void) {
// Define the Step Quantity Type
let stepsCount = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)
// Get the start of the day
let date = Date()
let cal = Calendar(identifier: Calendar.Identifier.gregorian)
let newDate = cal.startOfDay(for: date)
// Set the Predicates & Interval
let predicate = HKQuery.predicateForSamples(withStart: newDate, end: Date(), options: .strictStartDate)
var interval = DateComponents()
interval.day = 1
// Perform the Query
let query = HKStatisticsCollectionQuery(quantityType: stepsCount!, quantitySamplePredicate: predicate, options: [.cumulativeSum], anchorDate: newDate as Date, intervalComponents:interval)
query.initialResultsHandler = { query, results, error in
if error != nil {
// Something went Wrong
return
}
if let myResults = results{
myResults.enumerateStatistics(from: self.yesterday, to: self.today) {
statistics, stop in
if let quantity = statistics.sumQuantity() {
let steps = quantity.doubleValue(for: HKUnit.count())
print("Steps = \(steps)")
completion(stepRetrieved: steps)
}
}
}
}
storage.execute(query)
}
Objective-C
HKQuantityType *type = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
NSDate *today = [NSDate date];
NSDate *startOfDay = [[NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian] startOfDayForDate:today];
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startOfDay endDate:today options:HKQueryOptionStrictStartDate];
NSDateComponents *interval = [[NSDateComponents alloc] init];
interval.day = 1;
HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:type quantitySamplePredicate:predicate options:HKStatisticsOptionCumulativeSum anchorDate:startOfDay intervalComponents:interval];
query.initialResultsHandler = ^(HKStatisticsCollectionQuery * _Nonnull query, HKStatisticsCollection * _Nullable result, NSError * _Nullable error) {
if (error != nil) {
// TODO
} else {
[result enumerateStatisticsFromDate:startOfDay toDate:today withBlock:^(HKStatistics * _Nonnull result, BOOL * _Nonnull stop) {
HKQuantity *quantity = [result sumQuantity];
double steps = [quantity doubleValueForUnit:[HKUnit countUnit]];
NSLog(@"Steps : %f", steps);
}];
}
};
[self.storage executeQuery:query];
how to get totalDistance of HKWorkout
Add your distance samples to HKWorkoutBuilder
using its addSamples method. The total distance will be calculated for you based on the samples you add. e.g you can add samples of type HKQuantityTypeIdentifierDistanceWalkingRunning
to the workout and it should populate totalDistance
.
Related Topics
Convert Optional String to Int in Swift
How to Insert a Sublayer in Swift
How to Restrict an Enum to Certain Cases of Another Enum
Core Image Filter Cisourceovercompositing Not Appearing as Expected with Alpha Overlay
How to Split a String into a [String] and Not [Substring]
Unwrapping Optional in Swiftui View
Swift Any Difference Between Closures and First-Class Functions
"Raw Value for Enum Case Is Not Unique" for Swift Enum with Float Raw Values
How to Convert 4 Bytes to a Swift Float
Explit Conformance to Codable Removes Memberwise Initializer Generation on Structs
Xcode 7 Run on MAC Osx 10.10 Yosemite
Bringing iOS Frameworks Through Carthage in Xcode 12.0
Saving Coredata to a Web Server with Swift 3.0