Created
December 5, 2019 05:59
-
-
Save ochim/981fa55dd42cc0bc2a3a35a85d23311c to your computer and use it in GitHub Desktop.
[HealthKit]ヘルスケアデータにアクセスし、水泳のワークアウト、水泳のストローク数を取得し、出力する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import HealthKit | |
class ViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
guard HKHealthStore.isHealthDataAvailable() else { | |
return | |
} | |
let healthStore = HKHealthStore() | |
let readDataTypes: Set<HKObjectType> = [HKWorkoutType.workoutType(), | |
HKObjectType.quantityType(forIdentifier: .swimmingStrokeCount)!] | |
healthStore.requestAuthorization( | |
toShare: nil, | |
read: readDataTypes, | |
completion: {(success, error) in | |
if success { | |
let predicate = HKQuery.predicateForWorkouts(with: HKWorkoutActivityType.swimming) | |
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false) | |
let sampleQuery = HKSampleQuery( | |
sampleType: HKObjectType.workoutType(), | |
predicate: predicate, | |
limit: HKObjectQueryNoLimit, | |
sortDescriptors: [sortDescriptor], | |
resultsHandler: {(_, results, error) in | |
if error == nil { | |
let workouts = results as! [HKWorkout] | |
if let workout = workouts.first { | |
print(workout.workoutEvents) | |
let type = HKObjectType.quantityType(forIdentifier: .swimmingStrokeCount)! | |
guard let workoutEvents = workout.workoutEvents else { | |
return | |
} | |
for (index, workoutEvent) in workoutEvents.enumerated() { | |
// workoutEventのtypeにはlap, segment, pauseなどがあります | |
if workoutEvent.type == .lap { | |
let predicate = HKQuery.predicateForSamples(withStart: workoutEvent.dateInterval.start, end: workoutEvent.dateInterval.end, options: .strictStartDate) | |
let query = HKStatisticsQuery(quantityType: type, | |
quantitySamplePredicate: predicate, | |
options: [.cumulativeSum]) { (_, statistic, error) in | |
guard let statistic = statistic, error == nil else { | |
return | |
} | |
let sum = statistic.sumQuantity()?.doubleValue(for: HKUnit.count()) ?? 0 | |
print("stroke:\(sum) index:\(index)") | |
} | |
healthStore.execute(query) | |
} | |
} | |
} | |
} | |
}) | |
healthStore.execute(sampleQuery) | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment