Haptic Feedback with Sound in SwiftUI – sensoryFeedback
In my previous tutorial, I explained how to use .sensoryFeedback in SwiftUI. Now, in this tutorial, I will show you how we can add sound effect along with haptic effect.
Unfortunately till now, SwiftUI has no built-in feature to produce sound along with sensoryFeedback
. But I think this is fair enough because we can always add sound effects using AVFoundation
.
However, on their official documentation, I found a line saying that it would produce haptic or sound feedback. But I never figured out how to do that using sensoryFeedback
.
Some may find this post as a misleading title as I am going to use AVFoundation here, but right now I only find this as a working solution for me. If you find a better option you can write that in the comment section below.
Let’s start by creating a simple Button and on button press it will produce haptic feedback.
import SwiftUI struct ContentView: View { @State private var myValue = 0 var body: some View { Button("You pressed me \(myValue) times"){ myValue = myValue + 1 } .sensoryFeedback(.impact(weight: .light, intensity: 1), trigger: myValue) } }
Now it’s time to add a sound effect with that button.
First, we will need to add this line to import AVFoundation
import AVFoundation
For playing system sounds we can use this:
AudioServicesPlaySystemSound(audio_id)
Play sound with haptic feedback in SwiftUI
Let’s see an example:
import SwiftUI import AVFoundation struct ContentView: View { @State private var myValue = 0 var body: some View { Button("You pressed me \(myValue) times"){ myValue = myValue + 1 AudioServicesPlaySystemSound(1104) } .sensoryFeedback(.impact(weight: .light, intensity: 1), trigger: myValue) } }
This will produce the keypad pressing sound effect with haptic feedback.
If you wish to find a list of all the sounds you can check this:
https://iphonedev.wiki/AudioServices
You can get almost every type of sound effects from that list.
AudioServicesPlaySystemSound(1104)
this will produce the exact same sound as keypad pressing in iPhone default keyboard.
Leave a Reply