如何在watchOS中运行后台进程?

时间:2018-06-08 09:32:11

标签: swift watch-os watch-os-3

我已经制作了第一款苹果手表应用程序,并且每10秒钟就无法向我的后端发送数据。

当显示屏开启时,应用程序将被冻结,并在显示开启时从头开始再次运行。

我尝试像this example一样运行锻炼课程。

但它没有帮助,应用程序在10秒不活动后被冻结。

我尝试在InterfaceController.swift中每10秒向我的后端发送一次加速计数据:

//...
override func willActivate() {
    super.willActivate()
    startWorkout() //it's copied from example
    startAnglesTracker()
}

func startAnglesTracker() {
    if motion.isAccelerometerAvailable && !motion.isAccelerometerActive {
        motion.accelerometerUpdateInterval = 10
        motion.startAccelerometerUpdates(to: OperationQueue.main) {
            //sending here
        }
    }
}

private func startWorkout() {
    let workoutConfiguration = HKWorkoutConfiguration()
    workoutConfiguration.activityType = .crossTraining
    workoutConfiguration.locationType = .indoor
    do {
        workoutSession = try HKWorkoutSession(configuration: workoutConfiguration)
        workoutSession?.delegate = self
        healthStore.start(workoutSession!)
        vibrate()
    } catch {
        serverData.setText("workoutSession error")
    }
}
//...

extension InterfaceController: HKWorkoutSessionDelegate {
    func workoutSession(_ workoutSession: HKWorkoutSession, didFailWithError error: Error) {

    }

    func workoutSession(_ workoutSession: HKWorkoutSession, didGenerate event: HKWorkoutEvent) {

    }

    func workoutSession(_ workoutSession: HKWorkoutSession, didChangeTo toState: HKWorkoutSessionState, from fromState: HKWorkoutSessionState, date: Date) {

    }
}

仅在显示处于活动状态时才有效。

0 个答案:

没有答案