如何在watchOS和iOS上在后台运行函数?

如何在watchOS和iOS上在后台运行函数?,ios,swift,background,watchos,Ios,Swift,Background,Watchos,我正在尝试在iOS和watchOS的后台运行一个函数,我找到了一个代码示例,但它对我不起作用 我尝试了在GitHub上找到的一些示例代码和一个分派线程函数 。。。。。。。。。。 私人func startWorkout(){ 让workoutConfiguration=HKWorkoutConfiguration() workoutConfiguration.activityType=.other 做{ workoutSession=尝试HKWorkoutSession(healthStore:h

我正在尝试在iOS和watchOS的后台运行一个函数,我找到了一个代码示例,但它对我不起作用

我尝试了在GitHub上找到的一些示例代码和一个分派线程函数

。。。。。。。。。。
私人func startWorkout(){
让workoutConfiguration=HKWorkoutConfiguration()
workoutConfiguration.activityType=.other
做{
workoutSession=尝试HKWorkoutSession(healthStore:healthStore,配置:workoutConfiguration)
workoutSession?.delegate=self
//HKWorkoutSession.startActivity(workoutSession!)
healthStore.start(训练课程!)
}抓住{
打印(错误)
}
}
@objc fileprivate func振动(){
WKInterfaceDevice.current().play(.success)
}
........
扩展接口控制器:HKWorkoutSessionDelegate{
func workoutSession(workoutSession:HKWorkoutSession,DIDFailWither错误:错误){
}
func workoutSession(workoutSession:HKWorkoutSession,didGenerate事件:HKWorkoutEvent){
}
func workoutSession(workoutSession:HKWorkoutSession,DID更改为状态:HKWorkoutSessionState,从状态:HKWorkoutSessionState,日期:日期){
开关状态{
案例.运行:
hapticFeedbackTimer=计时器(时间间隔:0,目标:self,选择器:#选择器(振动),用户信息:nil,重复:true)
RunLoop.main.add(hapticFeedbackTimer!,forMode:.默认)
违约:
hapticFeedbackTimer?.invalidate()
触觉反馈定时器=零
}
}
}```
我希望函数振动在后台运行,但是没有发生任何事情

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

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()
            }
        }
    }
}
}

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

,所以我尝试了这个func scheduledTimerWithTimeInterval(){//scheduledTimer调用函数“updateCounting”,间隔为1秒print(delayTime)timer=timer.scheduledTimer(时间间隔:0.01,目标:self,选择器:#选择器(self.VibractWatch),userInfo:nil,repeats:true)DispatchQueue.backgroundQueue(self.vibrateWatch,completion:.none)}```但它不起作用。我做得不对吗?
vibrateWatch
有什么作用?基本上是简化的
wkInterfacedDevice.current().play(WKHapticType.click)
无法在后台运行VibrationWatch?来自apple docs后台线程描述:此工作对用户不可见。备份、同步、索引。因此请使用主线程。为什么要在后台线程中执行此操作?