如何在watchOS和iOS上在后台运行功能?

时间:2019-05-17 14:01:47

标签: ios swift background watch-os

我试图在iOS和watchOS的后台运行一个函数,但我发现了一个代码示例,但是对我来说不起作用。

我尝试了一些在GitHub上找到的示例代码以及一个调度线程函数。

..........
    private func startWorkout() {
        let workoutConfiguration = HKWorkoutConfiguration()
        workoutConfiguration.activityType = .other

        do {
            workoutSession = try HKWorkoutSession(healthStore: healthStore, configuration: workoutConfiguration)
            workoutSession?.delegate = self
//            HKWorkoutSession.startActivity(workoutSession!)
            healthStore.start(workoutSession!)
        } catch {
            print(error)
        }
    }

    @objc fileprivate func vibrate() {
        WKInterfaceDevice.current().play(.success)
    }


........

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) {
        switch toState {
        case .running:
            hapticFeedbackTimer = Timer(timeInterval: 0, target: self, selector: #selector(vibrate), userInfo: nil, repeats: true)
            RunLoop.main.add(hapticFeedbackTimer!, forMode: .default)
        default:
            hapticFeedbackTimer?.invalidate()
            hapticFeedbackTimer = nil
        }
    }
}```

I expected the function vibrate to be run in the background, but instead, nothing happened

1 个答案:

答案 0 :(得分:-1)

要使用后台线程,可以使用以下扩展名:

extension DispatchQueue {
static func backgroundQueue(_ backgroundOperations: ( () -> Void )? = nil, completion: (() -> Void)? = nil) {
    DispatchQueue.global(qos: .background).async {
        backgroundOperations?()
        if let completion = completion {
            DispatchQueue.main.async {
                completion()
            }
        }
    }
}
}

因此您可以在后台执行操作,然后在后台完成后在主线程上执行一些操作