Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make iPhone vibrate using Swift?

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.

like image 479
Nico Gutraich Avatar asked Oct 19 '14 22:10

Nico Gutraich


People also ask

How do I make my iPhone vibrate in Swift?

To make an iPhone vibrate using swift we'll use two different methods. First create a new project and add Four different buttons to the main View controller. Now import the AudioToolbox framework in your view controller class. This will generate a long vibrating feedback on your device.


2 Answers

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

like image 176
Steve Rosenberg Avatar answered Sep 24 '22 17:09

Steve Rosenberg


In iOS 10 on iPhone 7 or 7 Plus, try:

let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() 
like image 40
Adam Smaka Avatar answered Sep 24 '22 17:09

Adam Smaka