How to make iPhone vibrate using Swift?

Nico Gutraich picture Nico Gutraich · Oct 20, 2014 · Viewed 79.8k times · Source

I need to make the iPhone vibrate, but I don't know how to do that in Swift. I know that in Objective-C, you just write:

import AudioToolbox
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);

But that is not working for me.

Answer

Steve Rosenberg picture Steve Rosenberg · Oct 20, 2014

Short example:

import UIKit
import AudioToolbox

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))            
    }
}

load onto your phone and it will vibrate. You can put it in a function or IBAction as you wish.

Code Update:

 AudioServicesPlayAlertSoundWithCompletion(SystemSoundID(kSystemSoundID_Vibrate)) { }

As apple code docs written:

This function will be deprecated in a future release. Use AudioServicesPlaySystemSoundWithCompletion instead.

NOTE: If vibrate doesn't work. check vibrate is enable in sounds and haptics settings