Search code examples
swiftswiftuiiphone-vibrate

SwiftUI: How to make phone vibrate?


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

Solution

  • 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)) {   }
                   
                }
                
            }
            
        }
    }