0

I'm trying to run a function in the background on iOS and watchOS, and I found a code sample, but it didn't work for me.

I tried some sample code that I found on GitHub, and a dispatch thread function.

..........
    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
trainboy2019
  • 73
  • 10

1 Answers1

-1

to use the background thread you can use this extension:

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

so you can perform your actions in background and then, after the background finish, do something on main Thread

Alastar
  • 1,284
  • 1
  • 8
  • 14
  • So I tried this. ``` func scheduledTimerWithTimeInterval(){ // Scheduling timer to Call the function "updateCounting" with the interval of 1 seconds print(delayTime) timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(self.vibrateWatch), userInfo: nil, repeats: true) DispatchQueue.backgroundQueue(self.vibrateWatch, completion: .none) }``` and it didn't work. Did I not do this correct? – trainboy2019 May 17 '19 at 14:31
  • what does `vibrateWatch` does? – Alastar May 17 '19 at 14:37
  • Simplified, basically ```WKInterfaceDevice.current().play(WKHapticType.click)``` – trainboy2019 May 17 '19 at 14:38
  • 1
    there's no way to run vibrateWatch in the background? – trainboy2019 May 17 '19 at 14:51
  • from the apple docs background thread description: **This work isn’t visible to the user. Backups, syncs, indexing**. So use main thread. Why do you want to execute that in the background thread? – Alastar May 17 '19 at 14:58
  • Some people, like me, find that vibrations help calm them when they're nervous, like during meetings. That's why I want to make this. – trainboy2019 May 17 '19 at 15:04
  • So how would I accomplish what I'm trying to do? – trainboy2019 May 17 '19 at 15:10