Play Vibration iOS Tutorial

The iPhone has the built-in ability to alert the user with a vibration. Using the System Sound services the vibration can be triggered. In this tutorial the vibration will be triggered 5 times. Note this app is built for a real devices, since the iOS Simulator doesn't have vibration. This tutorial is made with Xcode 10 and built for iOS 12.

Open Xcode and create a new Single View App.

For product name, use IOSVibrationTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Go to the Storyboard. Drag a Button from the Object Library to the top of the main View. Double-click the Button and set the title to "Start". Select the "Resolve Auto Layout Issues" button on the bottom-right of the Interface Builder and choose "Reset to Suggested Constraints"

The Storyboard should look like this

Select the Assistant Editor and make sure the ViewController.swift is visible. Ctrl and drag from the Button and create the following Action.

Go to the ViewController.swift file and import the AudioToolbox framework

import AudioToolbox

Implement the startVibration method.

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

The AudioServicesPlaySystemSound method plays the vibration using the kSystemSoundID_Vibrate constant.The sleep delays 1 second for the next vibration starts, otherwise the vibration is still running. Build and Run the project on an iPhone, press the start button and the device will vibrate 5 times.

You can download the source code of the IOSVibrationTutorial at the ioscreator repository on Github.