Date post: | 05-Aug-2015 |
Category: |
Engineering |
Upload: | yusuke-kita |
View: | 1,934 times |
Download: | 5 times |
How to makeworkout appfor watchOS 2
Mercari Inc.@kitasuke
HealthKit
“Apps can use to share health and fitness data”HealthKit Framework Reference
Sample Objects» Characteristics
» Samples
» Category Samples
» Quantity Samples
» Correlations
» Workouts
Main flow for workout apps» Start workout session
» Query data in HealthKit
» Stop workout session
» Save data in HealthKit
What's Workout Session» Workout sessions allow apps to run in the
foreground
» Apple Watch can only run one workout session at a time
Workout Sessionclass HKWorkoutSession: NSObject {
var activityType: HKWorkoutActivityType { get } var locationType: HKWorkoutSessionLocationType { get } weak var delegate: HKWorkoutSessionDelegate? var state: HKWorkoutSessionState { get }
init(activityType: HKWorkoutActivityType, locationType: HKWorkoutSessionLocationType)}
Workout Activity Typeenum HKWorkoutActivityType : UInt {
case Basketball case Fishing case Gymnastics case Hunting case MartialArts case Running case Soccer case Swimming case Walking case Yoga …
case Other}
Workout Location Typeenum HKWorkoutSessionLocationType : Int {
case Unknown case Indoor case Outdoor}
Workout Session delegateprotocol HKWorkoutSessionDelegate : NSObjectProtocol {
func workoutSession(workoutSession: HKWorkoutSession, didChangeToState toState: HKWorkoutSessionState, fromState: HKWorkoutSessionState, date: NSDate)
func workoutSession(workoutSession: HKWorkoutSession, didFailWithError error: NSError)}
Starting and Stopping Workout SessionshealthStore.startWorkoutSession(workoutSession) { (result: Bool, error: NSError?) -> Void in}
healthStore.stopWorkoutSession(workoutSession) { (result: Bool, error: NSError?) -> Void in}
Setup for HealthKit1.Enable capabilities in Xcode
2.Check availability
3.Instantiate an HKHealthStore object
4.Request authorization
WatchKit Extension
let healthStore = HKHealthStore()
if HKHealthStore.isHealthDataAvailable() { let energy = HKQuantityTypeIdentifierActiveEnergyBurned)! let walkingRunning = HKQuantityTypeIdentifierDistanceWalkingRunning)! let heartRate = HKQuantityTypeIdentifierHeartRate)! let cycling = HKQuantityTypeIdentifierDistanceCycling)!
let typesToShare = Set([HKWorkoutType.workoutType()]) let typesToRead = Set([ HKObjectType.quantityTypeForIdentifier(energy, HKObjectType.quantityTypeForIdentifier(walkingRunning, HKObjectType.quantityTypeForIdentifier(heartRate, HKObjectType.quantityTypeForIdentifier(cycling ]) healthStore.requestAuthorizationToShareTypes(typesToShare, readTypes: typesToRead, completion: { (result: Bool, error: NSError?) -> Void in })}
Containing iOS app
func applicationShouldRequestHealthAuthorization(application: UIApplication) { HKHealthStore().handleAuthorizationForExtensionWithCompletion { (result: Bool, error: NSError?) -> Void in }}
Accessing HealthKit Data» Direct method calls
» Sample query
» Observer query
» Anchored object query
» Statistics query
» Statistics collection query
» Correlation query
» Source query
Streaming Updateslet predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: nil, options: .None)
let type = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceCycling)!let distanceQuery = HKAnchoredObjectQuery(type: type, predicate: predicate, anchor: 0, limit: 0) { (query, samples, deletedObjects, anchor, error) -> Void in}
distanceQuery.updateHandler = { (query, samples, deletedObjects, anchor, error) -> Void in}
healthStore.executeQuery(distanceQuery)
Saving workoutlet workout = HKWorkout(activityType: activityType, startDate: startDate, endDate: endDate, duration: endDate.timeIntervalSinceDate(startDate), totalEnergyBurned: totalEnergyBurned, totalDistance: totalDistance, metadata: nil)
healthStore.saveObject(workout) { (result: Bool, error: NSError?) -> Void in}
How to DebugBetter debug on device, not simulator
Because- Setting location to City Run or City Bicycle Ride doesn't work for HealthKit- Need to save data in HealthKit manually- Big behavior differences between device and simulator
Known Issues?
Can not attach to process on device“Did the 'trust this computer' diaglog ever show on the watch? Unpairing and then re-pairing and restarting Xcode should have gotten you that prompt. The symptoms you are experiencing seem to indicate that this dialog was not presented after you upgraded.”On device watchOS debugging impossible
Workout Session doesn't keep in the foregroundMight be a bug?
HKWorkoutSession and keeping the app in the foregroundHaving a workout count toward green exercise ring
Infrequent UpdatesupdateHandler is not stable?
HKWorkoutSession with HKAnchoredObjectQuery has very infrequent updates
Battery useNot particularly workout app issue, but should be well-considered
Battery Use Worse
Summary» Can access to a bunch of fitness information
» Customizable for specific use
» So much pain to debug
Thank you