Skip to content

Instantly share code, notes, and snippets.

@leogdion
Last active June 15, 2018 19:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leogdion/7837a0f1fe21b66d441a3ce601d89d84 to your computer and use it in GitHub Desktop.
Save leogdion/7837a0f1fe21b66d441a3ce601d89d84 to your computer and use it in GitHub Desktop.
func startWorkoutWithHealthStore(_ healthStore: HKHealthStore,
andActivityType activityType: HKWorkoutActivityType,
withSampleTypes sampleTypes: [HKSampleType]) -> HKWorkoutSession {
let configuration = HKWorkoutConfiguration()
configuration.activityType = activityType
let session : HKWorkoutSession
do {
session = try HKWorkoutSession(configuration: configuration)
} catch let error {
// let the user know about the error
return
}
let queries = sampleTypes.map{
HKObserverQuery(sampleType: $0, predicate: nil, updateHandler: self.observerQuery)
}
for query in queries {
healthStore.execute(query)
}
healthStore.start(session)
self.session = session
self.healthStore = healthStore
return session
}
func observerQuery(_ query: HKObserverQuery,
hasCompleted completed: HKObserverQueryCompletionHandler,
withError error: Error?) {
guard let healthStore = self.healthStore else {
#warning("Throw Error Message to User if no healthStore available")
return
}
guard let sampleType = query.objectType as? HKSampleType else {
completed()
return
}
// only query for the latest value
let sort = [
NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)
]
let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: nil, limit: 1, sortDescriptors: sort, resultsHandler: self.sampleQuery)
healthStore.execute(sampleQuery)
}
func sampleQuery(_ query: HKSampleQuery,
withSamples samples: [HKSample]?,
andError error: Error?) {
guard let quantityType = query.objectType as? HKQuantityType else {
return
}
if let error = error {
#warning("Theres an error with the query")
return
}
guard let sample = samples?.first as? HKQuantitySample else {
#warning("Theres no sample with the query.")
return
}
DispatchQueue.main.async {
// update the UI here
}
}
func workoutBuilder(_ workoutBuilder: HKLiveWorkoutBuilder,
didCollectDataOf collectedTypes: Set<HKSampleType>) {
for sampleType in collectedTypes {
if let quantityType = sampleType as? HKQuantityType {
guard let statistic = workoutBuilder.statistics(for: quantityType) else {
continue
}
guard let quantity = statistic.mostRecentQuantity() else {
continue
}
DispatchQueue.main.async {
// update the UI based on the most recent quantitiy
}
} else {
// handle other HKSampleType subclasses
}
}
}
func startWorkoutWithHealthStore(_ healthStore: HKHealthStore,
andActivityType activityType: HKWorkoutActivityType
) -> HKWorkoutSession {
let configuration = HKWorkoutConfiguration()
configuration.activityType = activityType
let session : HKWorkoutSession
do {
session = try HKWorkoutSession(configuration: configuration)
} catch let error {
// let the user know about the error
return
}
healthStore.start(session)
self.session = session
self.healthStore = healthStore
return session
}
func startWorkoutWithHealthStore(_ healthStore: HKHealthStore, andActivityType activityType: HKWorkoutActivityType, withSampleTypes sampleTypes: [HKSampleType]) -> HKWorkoutSession {
let configuration = HKWorkoutConfiguration()
configuration.activityType = activityType
let session : HKWorkoutSession
do {
session = try HKWorkoutSession(healthStore: healthStore, configuration: configuration)
} catch let error {
// let the user know about the error
return
}
let builder = session.associatedWorkoutBuilder()
builder.delegate = self
builder.dataSource = HKLiveWorkoutDataSource(healthStore: healthStore, workoutConfiguration: configuration)
session.delegate = self
self.builder = builder
self.session = session
self.healthStore = healthStore
session.startActivity()
builder.beginCollection(withStart: Date()) { (success, error) in
// do something when the data collection begins
}
return session
}
func workoutSession(_ workoutSession: HKWorkoutSession,
didChangeTo toState: HKWorkoutSessionState,
from fromState: HKWorkoutSessionState,
date: Date) {
DispatchQueue.main.async {
// based on the change update the UI on the main thread
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment