SlideShare a Scribd company logo
Howto make
workoutapp
for watchOS 2
Mercari Inc.
@kitasuke
How to make workout app for watch os 2
How to make workout app for watch os 2
How to make workout app for watch os 2
How to make workout app for watch os 2
How to make workout app for watch os 2
How to make workout app for watch os 2
HealthKit
“Apps can useto
share healthand
fitness data”
HealthKit Framework Reference
Sample Objects
» Characteristics
» Samples
» Category Samples
» Quantity Samples
» Correlations
» Workouts
Main flowforworkoutapps
» Start workout session
» Query data in HealthKit
» Stop workout session
» Save data in HealthKit
What'sWorkoutSession
» Workout sessions allow apps to run in the
foreground
» Apple Watch can only run one workout session at a
time
WorkoutSession
class HKWorkoutSession: NSObject {
var activityType: HKWorkoutActivityType { get }
var locationType: HKWorkoutSessionLocationType { get }
weak var delegate: HKWorkoutSessionDelegate?
var state: HKWorkoutSessionState { get }
init(activityType: HKWorkoutActivityType,
locationType: HKWorkoutSessionLocationType)
}
WorkoutActivityType
enum HKWorkoutActivityType : UInt {
case Basketball
case Fishing
case Gymnastics
case Hunting
case MartialArts
case Running
case Soccer
case Swimming
case Walking
case Yoga
…
case Other
}
WorkoutLocationType
enum HKWorkoutSessionLocationType : Int {
case Unknown
case Indoor
case Outdoor
}
WorkoutSession delegate
protocol HKWorkoutSessionDelegate : NSObjectProtocol {
func workoutSession(workoutSession: HKWorkoutSession,
didChangeToState toState: HKWorkoutSessionState,
fromState: HKWorkoutSessionState, date: NSDate)
func workoutSession(workoutSession: HKWorkoutSession,
didFailWithError error: NSError)
}
Startingand StoppingWorkout
Sessions
healthStore.startWorkoutSession(workoutSession) {
(result: Bool, error: NSError?) -> Void in
}
healthStore.stopWorkoutSession(workoutSession) {
(result: Bool, error: NSError?) -> Void in
}
Setupfor HealthKit
1.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
}
}
How to make workout app for watch os 2
How to make workout app for watch os 2
Accessing HealthKitData
» Direct method calls
» Sample query
» Observer query
» Anchored object query
» Statistics query
» Statistics collection query
» Correlation query
» Source query
Streaming Updates
let 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)
Savingworkout
let 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
}
Howto Debug
Better 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 notattachto 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
WorkoutSession doesn'tkeepin
the foreground
Might be a bug?
HKWorkoutSession and keeping the app in the
foreground
Having a workout count toward green exercise ring
InfrequentUpdates
updateHandler is not stable?
HKWorkoutSession with HKAnchoredObjectQuery has very
infrequent updates
Batteryuse
Not 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
Thankyou

More Related Content

PDF
Search APIs in Spotlight and Safari
PDF
Server Side Swift with Swag
PDF
Search APIs & Universal Links
PDF
Node.js and Parse
PDF
第一次用Parse就深入淺出
PPTX
What's Parse
PPTX
Intro to Parse
PDF
Parse cloud code
Search APIs in Spotlight and Safari
Server Side Swift with Swag
Search APIs & Universal Links
Node.js and Parse
第一次用Parse就深入淺出
What's Parse
Intro to Parse
Parse cloud code

What's hot (20)

PDF
<x> Rails Web App Security Title
PPTX
Html indexed db
PPTX
Leveraging parse.com for Speedy Development
PPTX
Google cloud datastore driver for Google Apps Script DB abstraction
PPTX
Parse Advanced
PDF
Android search
DOCX
Working With Sharepoint 2013 Apps Development
PDF
async/await in Swift
PPTX
Sharepoint Saturday India Online best practice for developing share point sol...
PPTX
Lviv MDDay 2014. Ігор Коробка “забезпечення базової безпеки в андроїд аплікац...
PPTX
Leveraging Azure Search in Your Application
PDF
How To Manage API Request with AXIOS on a React Native App
PPTX
Share pointtechies linqtosp-andsbs
PPTX
Tips for Angular Applications
PPTX
Dbabstraction
PPTX
Google apps script database abstraction exposed version
PDF
Django 1.10.3 Getting started
PPTX
Building Web Apps with the Esri-Leaflet Plugin - Dubai DevSummit 2013
PDF
Appengine Java Night #2b
PPT
jQuery for beginners
<x> Rails Web App Security Title
Html indexed db
Leveraging parse.com for Speedy Development
Google cloud datastore driver for Google Apps Script DB abstraction
Parse Advanced
Android search
Working With Sharepoint 2013 Apps Development
async/await in Swift
Sharepoint Saturday India Online best practice for developing share point sol...
Lviv MDDay 2014. Ігор Коробка “забезпечення базової безпеки в андроїд аплікац...
Leveraging Azure Search in Your Application
How To Manage API Request with AXIOS on a React Native App
Share pointtechies linqtosp-andsbs
Tips for Angular Applications
Dbabstraction
Google apps script database abstraction exposed version
Django 1.10.3 Getting started
Building Web Apps with the Esri-Leaflet Plugin - Dubai DevSummit 2013
Appengine Java Night #2b
jQuery for beginners
Ad

Similar to How to make workout app for watch os 2 (20)

PDF
Swift Montevideo Meetup - iPhone, una herramienta medica
PDF
Swift Montevideo Meetup - iPhone, una herramienta medica
PDF
Azure Durable Functions (2019-03-30)
PDF
Flink Forward Berlin 2018: Jared Stehler - "Streaming ETL with Flink and Elas...
PPTX
Integration testing - Yasub Hashmi
PPTX
The uniform interface is 42
PDF
Azure Durable Functions (2019-04-27)
PDF
We Are All Testers Now: The Testing Pyramid and Front-End Development
PDF
Durable functions 2.0 (2019-10-10)
PDF
power-assert, mechanism and philosophy
PDF
Introducing Cardio
PDF
Know your app: Add metrics to Java with Micrometer | DevNation Tech Talk
PPTX
Adding a modern twist to legacy web applications
PPTX
Introduction to Software Testing
PPTX
[NDC 2019] Enterprise-Grade Serverless
PPTX
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
PDF
Struts2 - 101
PDF
Bonnes pratiques de développement avec Node js
PDF
Akka Testkit Patterns
PDF
Understanding backbonejs
Swift Montevideo Meetup - iPhone, una herramienta medica
Swift Montevideo Meetup - iPhone, una herramienta medica
Azure Durable Functions (2019-03-30)
Flink Forward Berlin 2018: Jared Stehler - "Streaming ETL with Flink and Elas...
Integration testing - Yasub Hashmi
The uniform interface is 42
Azure Durable Functions (2019-04-27)
We Are All Testers Now: The Testing Pyramid and Front-End Development
Durable functions 2.0 (2019-10-10)
power-assert, mechanism and philosophy
Introducing Cardio
Know your app: Add metrics to Java with Micrometer | DevNation Tech Talk
Adding a modern twist to legacy web applications
Introduction to Software Testing
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
Struts2 - 101
Bonnes pratiques de développement avec Node js
Akka Testkit Patterns
Understanding backbonejs
Ad

More from Yusuke Kita (20)

PDF
Integrating libSyntax into the compiler pipeline
PDF
Making your own tool using SwiftSyntax
PDF
[Deprecated] Integrating libSyntax into the compiler pipeline
PDF
Creating your own Bitrise step
PDF
Introducing swift-format
PDF
Unidirectional Data Flow Through SwiftUI
PDF
Open Source Swift Workshop
PDF
Contributing to Swift Compiler
PDF
Writing a compiler in go
PDF
Writing an interpreter in swift
PDF
SIL Optimizations - AllocBoxToStack
PDF
SIL for First Time Learners
PDF
var, let in SIL
PDF
SIL for First Time Leaners LT
PDF
How to try! Swift
PDF
SIL for the first time
PDF
Introducing protobuf in Swift
PDF
Type-safe Web APIs with Protocol Buffers in Swift at AltConf
PDF
Type-safe Web APIs with Protocol Buffers in Swift at iOSCon
PDF
Swift core
Integrating libSyntax into the compiler pipeline
Making your own tool using SwiftSyntax
[Deprecated] Integrating libSyntax into the compiler pipeline
Creating your own Bitrise step
Introducing swift-format
Unidirectional Data Flow Through SwiftUI
Open Source Swift Workshop
Contributing to Swift Compiler
Writing a compiler in go
Writing an interpreter in swift
SIL Optimizations - AllocBoxToStack
SIL for First Time Learners
var, let in SIL
SIL for First Time Leaners LT
How to try! Swift
SIL for the first time
Introducing protobuf in Swift
Type-safe Web APIs with Protocol Buffers in Swift at AltConf
Type-safe Web APIs with Protocol Buffers in Swift at iOSCon
Swift core

Recently uploaded (20)

PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PPTX
CURRICULAM DESIGN engineering FOR CSE 2025.pptx
PPTX
Nature of X-rays, X- Ray Equipment, Fluoroscopy
PPTX
Information Storage and Retrieval Techniques Unit III
PDF
UNIT no 1 INTRODUCTION TO DBMS NOTES.pdf
PPTX
Safety Seminar civil to be ensured for safe working.
PDF
Unit I ESSENTIAL OF DIGITAL MARKETING.pdf
PDF
EXPLORING LEARNING ENGAGEMENT FACTORS INFLUENCING BEHAVIORAL, COGNITIVE, AND ...
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PDF
Human-AI Collaboration: Balancing Agentic AI and Autonomy in Hybrid Systems
PDF
Level 2 – IBM Data and AI Fundamentals (1)_v1.1.PDF
PPT
Occupational Health and Safety Management System
PDF
Categorization of Factors Affecting Classification Algorithms Selection
PPT
introduction to datamining and warehousing
PPT
INTRODUCTION -Data Warehousing and Mining-M.Tech- VTU.ppt
PDF
SMART SIGNAL TIMING FOR URBAN INTERSECTIONS USING REAL-TIME VEHICLE DETECTI...
PDF
BIO-INSPIRED ARCHITECTURE FOR PARSIMONIOUS CONVERSATIONAL INTELLIGENCE : THE ...
PDF
86236642-Electric-Loco-Shed.pdf jfkduklg
PDF
BIO-INSPIRED HORMONAL MODULATION AND ADAPTIVE ORCHESTRATION IN S-AI-GPT
PDF
III.4.1.2_The_Space_Environment.p pdffdf
Automation-in-Manufacturing-Chapter-Introduction.pdf
CURRICULAM DESIGN engineering FOR CSE 2025.pptx
Nature of X-rays, X- Ray Equipment, Fluoroscopy
Information Storage and Retrieval Techniques Unit III
UNIT no 1 INTRODUCTION TO DBMS NOTES.pdf
Safety Seminar civil to be ensured for safe working.
Unit I ESSENTIAL OF DIGITAL MARKETING.pdf
EXPLORING LEARNING ENGAGEMENT FACTORS INFLUENCING BEHAVIORAL, COGNITIVE, AND ...
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
Human-AI Collaboration: Balancing Agentic AI and Autonomy in Hybrid Systems
Level 2 – IBM Data and AI Fundamentals (1)_v1.1.PDF
Occupational Health and Safety Management System
Categorization of Factors Affecting Classification Algorithms Selection
introduction to datamining and warehousing
INTRODUCTION -Data Warehousing and Mining-M.Tech- VTU.ppt
SMART SIGNAL TIMING FOR URBAN INTERSECTIONS USING REAL-TIME VEHICLE DETECTI...
BIO-INSPIRED ARCHITECTURE FOR PARSIMONIOUS CONVERSATIONAL INTELLIGENCE : THE ...
86236642-Electric-Loco-Shed.pdf jfkduklg
BIO-INSPIRED HORMONAL MODULATION AND ADAPTIVE ORCHESTRATION IN S-AI-GPT
III.4.1.2_The_Space_Environment.p pdffdf

How to make workout app for watch os 2

  • 1. Howto make workoutapp for watchOS 2 Mercari Inc. @kitasuke
  • 9. “Apps can useto share healthand fitness data” HealthKit Framework Reference
  • 10. Sample Objects » Characteristics » Samples » Category Samples » Quantity Samples » Correlations » Workouts
  • 11. Main flowforworkoutapps » Start workout session » Query data in HealthKit » Stop workout session » Save data in HealthKit
  • 12. What'sWorkoutSession » Workout sessions allow apps to run in the foreground » Apple Watch can only run one workout session at a time
  • 13. WorkoutSession class HKWorkoutSession: NSObject { var activityType: HKWorkoutActivityType { get } var locationType: HKWorkoutSessionLocationType { get } weak var delegate: HKWorkoutSessionDelegate? var state: HKWorkoutSessionState { get } init(activityType: HKWorkoutActivityType, locationType: HKWorkoutSessionLocationType) }
  • 14. WorkoutActivityType enum HKWorkoutActivityType : UInt { case Basketball case Fishing case Gymnastics case Hunting case MartialArts case Running case Soccer case Swimming case Walking case Yoga … case Other }
  • 15. WorkoutLocationType enum HKWorkoutSessionLocationType : Int { case Unknown case Indoor case Outdoor }
  • 16. WorkoutSession delegate protocol HKWorkoutSessionDelegate : NSObjectProtocol { func workoutSession(workoutSession: HKWorkoutSession, didChangeToState toState: HKWorkoutSessionState, fromState: HKWorkoutSessionState, date: NSDate) func workoutSession(workoutSession: HKWorkoutSession, didFailWithError error: NSError) }
  • 17. Startingand StoppingWorkout Sessions healthStore.startWorkoutSession(workoutSession) { (result: Bool, error: NSError?) -> Void in } healthStore.stopWorkoutSession(workoutSession) { (result: Bool, error: NSError?) -> Void in }
  • 18. Setupfor HealthKit 1.Enable capabilities in Xcode 2.Check availability 3.Instantiate an HKHealthStore object 4.Request authorization
  • 19. 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 }) }
  • 20. Containing iOS app func applicationShouldRequestHealthAuthorization(application: UIApplication) { HKHealthStore().handleAuthorizationForExtensionWithCompletion { (result: Bool, error: NSError?) -> Void in } }
  • 23. Accessing HealthKitData » Direct method calls » Sample query » Observer query » Anchored object query » Statistics query » Statistics collection query » Correlation query » Source query
  • 24. Streaming Updates let 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)
  • 25. Savingworkout let 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 }
  • 26. Howto Debug Better 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
  • 28. Can notattachto 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
  • 29. WorkoutSession doesn'tkeepin the foreground Might be a bug? HKWorkoutSession and keeping the app in the foreground Having a workout count toward green exercise ring
  • 30. InfrequentUpdates updateHandler is not stable? HKWorkoutSession with HKAnchoredObjectQuery has very infrequent updates
  • 31. Batteryuse Not particularly workout app issue, but should be well-considered Battery Use Worse
  • 32. Summary » Can access to a bunch of fitness information » Customizable for specific use » So much pain to debug