SlideShare ist ein Scribd-Unternehmen logo
1 von 33
Downloaden Sie, um offline zu lesen
Howto make
workoutapp
for watchOS 2
Mercari Inc.
@kitasuke
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
}
}
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

Weitere ähnliche Inhalte

Was ist angesagt?

Sharepoint Saturday India Online best practice for developing share point sol...
Sharepoint Saturday India Online best practice for developing share point sol...Sharepoint Saturday India Online best practice for developing share point sol...
Sharepoint Saturday India Online best practice for developing share point sol...
Shakir Majeed Khan
 
Share pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbsShare pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbs
Shakir Majeed Khan
 
Google apps script database abstraction exposed version
Google apps script database abstraction   exposed versionGoogle apps script database abstraction   exposed version
Google apps script database abstraction exposed version
Bruce McPherson
 
Building Web Apps with the Esri-Leaflet Plugin - Dubai DevSummit 2013
Building Web Apps with the Esri-Leaflet Plugin - Dubai DevSummit 2013Building Web Apps with the Esri-Leaflet Plugin - Dubai DevSummit 2013
Building Web Apps with the Esri-Leaflet Plugin - Dubai DevSummit 2013
Aaron Parecki
 
Appengine Java Night #2b
Appengine Java Night #2bAppengine Java Night #2b
Appengine Java Night #2b
Shinichi Ogawa
 

Was ist angesagt? (20)

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

Ähnlich wie How to make workout app for watch os 2

Ähnlich wie How to make workout app for watch os 2 (20)

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

Mehr von Yusuke Kita

Integrating libSyntax into the compiler pipeline
Integrating libSyntax into the compiler pipelineIntegrating libSyntax into the compiler pipeline
Integrating libSyntax into the compiler pipeline
Yusuke Kita
 

Mehr von Yusuke Kita (20)

Integrating libSyntax into the compiler pipeline
Integrating libSyntax into the compiler pipelineIntegrating libSyntax into the compiler pipeline
Integrating libSyntax into the compiler pipeline
 
Making your own tool using SwiftSyntax
Making your own tool using SwiftSyntaxMaking your own tool using SwiftSyntax
Making your own tool using SwiftSyntax
 
[Deprecated] Integrating libSyntax into the compiler pipeline
[Deprecated] Integrating libSyntax into the compiler pipeline[Deprecated] Integrating libSyntax into the compiler pipeline
[Deprecated] Integrating libSyntax into the compiler pipeline
 
Creating your own Bitrise step
Creating your own Bitrise stepCreating your own Bitrise step
Creating your own Bitrise step
 
Introducing swift-format
Introducing swift-formatIntroducing swift-format
Introducing swift-format
 
Unidirectional Data Flow Through SwiftUI
Unidirectional Data Flow Through SwiftUIUnidirectional Data Flow Through SwiftUI
Unidirectional Data Flow Through SwiftUI
 
Open Source Swift Workshop
Open Source Swift WorkshopOpen Source Swift Workshop
Open Source Swift Workshop
 
Contributing to Swift Compiler
Contributing to Swift CompilerContributing to Swift Compiler
Contributing to Swift Compiler
 
Writing a compiler in go
Writing a compiler in goWriting a compiler in go
Writing a compiler in go
 
Writing an interpreter in swift
Writing an interpreter in swiftWriting an interpreter in swift
Writing an interpreter in swift
 
SIL Optimizations - AllocBoxToStack
SIL Optimizations - AllocBoxToStackSIL Optimizations - AllocBoxToStack
SIL Optimizations - AllocBoxToStack
 
SIL for First Time Learners
SIL for First Time LearnersSIL for First Time Learners
SIL for First Time Learners
 
var, let in SIL
var, let in SILvar, let in SIL
var, let in SIL
 
SIL for First Time Leaners LT
SIL for First Time Leaners LTSIL for First Time Leaners LT
SIL for First Time Leaners LT
 
How to try! Swift
How to try! SwiftHow to try! Swift
How to try! Swift
 
SIL for the first time
SIL for the first timeSIL for the first time
SIL for the first time
 
Introducing protobuf in Swift
Introducing protobuf in SwiftIntroducing protobuf in Swift
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 AltConfType-safe Web APIs with Protocol Buffers in Swift at AltConf
Type-safe Web APIs with Protocol Buffers in Swift at AltConf
 
Type-safe Web APIs with Protocol Buffers in Swift at iOSCon
Type-safe Web APIs with Protocol Buffers in Swift at iOSConType-safe Web APIs with Protocol Buffers in Swift at iOSCon
Type-safe Web APIs with Protocol Buffers in Swift at iOSCon
 
Swift core
Swift coreSwift core
Swift core
 

Kürzlich hochgeladen

Digital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxDigital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptx
pritamlangde
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Kürzlich hochgeladen (20)

data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
Digital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxDigital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptx
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and properties
 
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)
 

How to make workout app for watch os 2

  • 1. Howto make workoutapp for watchOS 2 Mercari Inc. @kitasuke
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 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 } }
  • 21.
  • 22.
  • 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