大多数HealthKit示例代码都使用InterfaceController
充当HKWorkoutSessionDelegate
,但是我尝试设置一个HealthStoreManager类作为HKWorkoutSessionDelegate,并将此业务逻辑从我个人的InterfaceControllers
职责中解放出来,但是以下代码失败开始锻炼,谁能看到我的错误?
InterfaceController: {
func segueToWorkoutInterfaceControllerWithContext() {
// Create workout configuration
let workoutConfiguration = HKWorkoutConfiguration()
workoutConfiguration.activityType = .running
workoutConfiguration.locationType = .outdoor
do {
let workoutSession = try HKWorkoutSession(configuration: workoutConfiguration)
let healthStoreManager = HealthStoreManager()
workoutSession.delegate = healthStoreManager
healthStoreManager.start(workoutSession)
} catch {
fatalError(error.localizedDescription)
}
let contextDictionary = ["workoutConfiguration" : workoutConfiguration, "ActivityType": selectedActivityType] as [String : Any]
// Pass configuration to next interface controller
WKInterfaceController.reloadRootPageControllers(withNames: ["WorkoutControlsInterfaceController", "MainDisplayInterfaceController", "SpeedInterfaceController", "CaloriesAndDistanceInterfaceController"],
contexts: [contextDictionary],
orientation: .horizontal,
pageIndex: 1)
}
}
}
class HealthStoreManager: NSObject, CLLocationManagerDelegate, HKWorkoutSessionDelegate {
private let healthStore = HKHealthStore()
// MARK: - HKWorkoutSessionDelegate
func workoutSession(_ workoutSession: HKWorkoutSession, didFailWithError error: Error) {
print("workout session did fail with error: \(error)")
}
func workoutSession(_ workoutSession: HKWorkoutSession,
didChangeTo toState: HKWorkoutSessionState,
from fromState: HKWorkoutSessionState,
date: Date) {
DispatchQueue.main.async {
self.handleWorkoutSessionState(didChangeTo: toState, from: fromState)
}
}
func workoutSession(_ workoutSession: HKWorkoutSession, didGenerate event: HKWorkoutEvent) {
DispatchQueue.main.async {
//self.healthStoreManager.workoutEvents.append(event)
}
}
private func handleWorkoutSessionState(didChangeTo toState: HKWorkoutSessionState,
from fromState: HKWorkoutSessionState) {
switch (fromState, toState) {
case (.notStarted, .running):
print("workout started")
case (_, .ended):
default:
break
}
}
}
最佳答案
我发现了我的错误,我需要将healthStoreManager实例传递到上下文中,以避免释放此类:
let contextDictionary = ["workoutConfiguration" : workoutConfiguration, "ActivityType": selectedActivityType, "healthStoreManager" : healthStoreManager] as [String : Any]
关于ios - 如何设置不是InterfaceController的HKWorkoutSessionDelegate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49910769/