NEW: Master Swift design patterns with my latest book! >>

How to make the device vibrate

Written by Paul Hudson    @twostraws

All iPhones have a built-in motor to create vibration effects, and if you just want a quick vibration it takes just one line of code:

AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)

You’ll need to import the AVFoundation framework if you don’t have it already.

That’s not a particularly easy line of code to remember, so why not make it an extension on UIDevice?

extension UIDevice {
    static func vibrate() {
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
    }
}

Now you can just call UIDevice.vibrate() as needed.

Available from iOS 2.0

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Get six books for only $150

The Swift Power Pack includes my first six books for one low price, helping you jumpstart a new career in iOS development – check it out!

Click here to visit the Hacking with Swift store >>