Reputation: 53
I'm developing an application for Apple Watch that acquires accelerometer, gyroscope data through DeviceMotion, and heart rate through HKWorkout.
Until the application stays in the foreground, all works well. However, when it enters the inactive state (when the user lowers the wrist), for some time it works, but at a certain point it stops. Furthermore, when the app goes in background, the app stops to collect new DeviceMotion updates, but I think that the observer of the heart rate continues to work since the green led still remains on.
The code I use for DeviceMotion is:
if self.motion.isDeviceMotionAvailable {
self.motion.deviceMotionUpdateInterval = 1.0 / 100.0
self.motion.showsDeviceMovementDisplay = true
self.motion.startDeviceMotionUpdates(using: .xMagneticNorthZVertical, to: OperationQueue.main, withHandler: { (data, error) in
if let d = data {
//collecting data
}
}
}
The code I use for heart rate:
let workoutConfiguration = HKWorkoutConfiguration()
workoutConfiguration.activityType = .crossTraining
workoutConfiguration.locationType = .indoor
do {
if workoutSession == nil {
workoutSession = try HKWorkoutSession(healthStore: HealthDataManager.sharedInstance.healthStore!, configuration: workoutConfiguration)
workoutSession?.startActivity(with: Date())
}
} catch {
print("Error starting workout session: \(error.localizedDescription)")
}
HealthDataManager.sharedInstance.observeHeartRateSamples { (heartRate) -> (Void) in
print("heart rate sample: \(heartRate)")
self.lastHearRateSample = heartRate
}
Since Apple Documentation states (https://developer.apple.com/documentation/healthkit/workouts_and_activity_rings)
While a workout session is active, your app can continue to run in the background. This lets your app monitor the user and gather data throughout the activity. Additionally, it ensures that your app appears whenever the user checks their watch.
I have thought that there was no need to manage the behavior of the app in these cases. However, it seems that something must be done. What's the best way to collect new DeviceMotion data also in the background state (and in the inactive one)?
Upvotes: 0
Views: 338
Reputation: 53
It turned out that the application went in the background because of the health kit workout. However, I was using too many resources and the system suspended the app.
Upvotes: 0