Sequence of haptic feedback impacts

40 Views Asked by At

I have a property @Published var shouldAnimateChatTabIcon: Bool. In the view's modifier .onChange(of: tabBarStateManager.shouldAnimateChatTabIcon), based on shouldAnimateChatTabIcon value, I want to execute a function and generate continuous haptic feedback. I want to generate repeating sequence of 3 haptic impacts:

UIImpactFeedbackGenerator.light.impactOccurred()
UIImpactFeedbackGenerator.medium.impactOccurred()
UIImpactFeedbackGenerator.heavy.impactOccurred()

This sequence should repeat until shouldAnimateChatTabIcon is false. Between every impact there should be delay of 0.8 seconds and the same delay should be between both sequences.

I thought of using three DispatchQueue.main.asyncAfter executors with no success though - there was only one impact or none. The same outcome was when trying to use async/await with Task inside .onChange as @jnpdx suggested

.onChange(of: tabBarStateManager.shouldAnimateChatTabIcon) { _, shouldStart in
            if shouldStart {
                Task {
                    UIImpactFeedbackGenerator(style: .light).impactOccurred()
                    try? await Task.sleep(nanoseconds: 800_000_000)
                    UIImpactFeedbackGenerator(style: .medium).impactOccurred()
                    try? await Task.sleep(nanoseconds: 800_000_000)
                    UIImpactFeedbackGenerator(style: .heavy).impactOccurred()
                    try? await Task.sleep(nanoseconds: 800_000_000)
                }
            }
        }

I searched other posts and found out that haptic feedback does not work when using microphone which was exactly what I was trying to do. https://stackoverflow.com/a/52450237/14793963.

Tried without microphone usage and @jnpdx solution worked fine. Is there any way to avoid this restriction and trigger haptic feedback during microphone usage?

0

There are 0 best solutions below