How to make iPhone vibrate using Swift?

iOSiPhone/iPadMobile DevelopmentSwift

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.

For the first button add an action and write the following code as shown below:

@IBAction func actionButtonOne(_ sender: Any) {
   AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
}

This will generate a long vibrating feedback on your device. Now to create more vibration effects on devices with iOS 10 or more we’ll add methods for all four different buttons.

@IBAction func actionButtonTwo(_ sender: Any) {
   let generator = UIImpactFeedbackGenerator(style: .heavy)
   generator.impactOccurred()
}
@IBAction func actionButtonThree(_ sender: Any) {
   let generator = UIImpactFeedbackGenerator(style: .light)
   generator.impactOccurred()
}
@IBAction func actionButtonFour(_ sender: Any) {
   let generator = UIImpactFeedbackGenerator(style: .medium)
   generator.impactOccurred()
}

In the above three methods, we are using UIImpact Feedback generator to generate three different types of feedback. Now run the application on a device and feel the vibrations when you press these buttons. Sadly the output can not be shown in this example as it is a vibration feedback.

raja
Published on 21-Jan-2019 17:00:52
Advertisements