How to make iPhone vibrate using Swift?
In iOS 10 on iPhone 7 or 7 Plus, try:
let generator = UIImpactFeedbackGenerator(style: .heavy)
generator.impactOccurred()
Swift 4.2 Updated
Just insert code below into your project.
Usage
Vibration.success.vibrate()
Source Code
enum Vibration {
case error
case success
case warning
case light
case medium
case heavy
@available(iOS 13.0, *)
case soft
@available(iOS 13.0, *)
case rigid
case selection
case oldSchool
public func vibrate() {
switch self {
case .error:
UINotificationFeedbackGenerator().notificationOccurred(.error)
case .success:
UINotificationFeedbackGenerator().notificationOccurred(.success)
case .warning:
UINotificationFeedbackGenerator().notificationOccurred(.warning)
case .light:
UIImpactFeedbackGenerator(style: .light).impactOccurred()
case .medium:
UIImpactFeedbackGenerator(style: .medium).impactOccurred()
case .heavy:
UIImpactFeedbackGenerator(style: .heavy).impactOccurred()
case .soft:
if #available(iOS 13.0, *) {
UIImpactFeedbackGenerator(style: .soft).impactOccurred()
}
case .rigid:
if #available(iOS 13.0, *) {
UIImpactFeedbackGenerator(style: .rigid).impactOccurred()
}
case .selection:
UISelectionFeedbackGenerator().selectionChanged()
case .oldSchool:
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
}
}
}
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