SwiftUI: How to make phone vibrate?

3.1k Views Asked by At

So I understand how to make the phone give haptic feedback through this tutorial. https://swifttom.com/2020/03/11/haptic-feedback-in-a-swiftui-button/

However, what I'm trying to figure out is how to make the iPhone actually vibrate, as in the vibration that occurs when receiving a phone call or a timer (from the default Clock app) going off while the phone is muted. I know this seems like I can find the answer easily on Google, but I honestly can't find a solution. Would be much appreciate if anyone can help.

import SwiftUI

struct ContentView: View {
    let generator = UINotificationFeedbackGenerator()
    var body: some View {
        VStack{
            Button("Press") {
                generator.notificationOccurred(.error) //I want vibration, not haptic feedback
            }
        }
    }
}
3

There are 3 best solutions below

0
geethsg7 On BEST ANSWER

This should help a little I think. Try it out! Lmk if it works!

Source Code

import SwiftUI
import AudioToolbox


struct ContentView: View {
    var body: some View {
        VStack{
            
            Button("Press"){
                AudioServicesPlayAlertSoundWithCompletion(SystemSoundID(kSystemSoundID_Vibrate)) {   }
               
            }
            
        }
        
    }
}
1
Adam On

Just call AudioServicesPlaySystemSound(kSystemSoundID_Vibrate). You may need to import the AudioToolbox framework.

2
Karan Mehra On

1. first you need to import AudioToolbox

i'm using vibration functionality when i tap button.

@IBAction func startVibration(_ sender: Any) { for _ in 1...5 { AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) sleep(1) } }

its work fine.

2. make it an extension on UIDevice?

extension UIDevice { static func vibrate() { AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) } }

Now you can just call UIDevice.vibrate() as needed.