How To Make The Device Vibrate Or Ring- An iOS Swift Tutorial

The iPhones have a built-in ability to alert users by creating some vibration or sound effects. You can trigger the vibration or sound effects by using SystemSound services. This is very useful in many cases while working on iOS Apps. in this tutorial, we’ll learn how to trigger the vibration or sound effect on any particular action or button clicks.

This is very easy to do and just takes one or 2 lines of code. In this tutorial, I’ll just write the code that you need to add in your button’s action or any other specific function to make the device vibrate or sound + vibrate both. We’ll also see how to make the device vibrate more than once. So let’s start..

Before anything, make sure to import AVFoundation.

For Vibrate Only:

If you only want to make the device quick vibrate, then this one line of code will do the trick:

AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)


For Sound & Vibrate Both:

If you want to make your device vibrate plus sound both, then you can use this one line of code:

AudioServicesPlaySystemSound(SystemSoundID(1003))

 

Bonus:

If you want to make your device vibrate or sound more than once, you can use ‘for loop’ or simply use following code:

for _ in 15 {
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
    sleep(1)
}

So simple, right? So by using this code, your device will vibrate 5 times. Sleep will delay 1 second for triggering the next vibration.

==> In above provided code snippets, The AudioServicesPlaySystemSound is the inbuilt method which will trigger the vibrate using the kSystemSoundID_Vibrate or trigger the sound+vibrate both using the SystemSoundID(1003)constant. Here, 1003 is the SystemSoundID. You can use other sound Ids too. There’s a list of all system sound Ids available on this link..

This is easy to trigger vibrations in your device using this inbuilt sound services. I hope you’ll like this little tutorial. If you’ve any issues or need any further help, do message me in the comments section below and I’ll try my best to reply you as soon as possible.

Thanks for you time. Keep Coding.. 👨‍💻