I need to make the iPhone vibrate, but I don\'t know how to do that in Swift. I know that in Objective-C, you just write:
import AudioToolbox
AudioServicesPl
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))
}
}
}
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
import AudioToolbox
extension UIDevice {
static func vibrate() {
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
}
}
Now you can just call UIDevice.vibrate()
as needed.
In iOS 10 on iPhone 7 or 7 Plus, try:
let generator = UIImpactFeedbackGenerator(style: .heavy)
generator.impactOccurred()
Other vibration types:
import AudioToolbox
AudioServicesPlaySystemSound(1519) // Actuate "Peek" feedback (weak boom)
AudioServicesPlaySystemSound(1520) // Actuate "Pop" feedback (strong boom)
AudioServicesPlaySystemSound(1521) // Actuate "Nope" feedback (series of three weak booms)
More About Vibration - http://www.mikitamanko.com/blog/2017/01/29/haptic-feedback-with-uifeedbackgenerator/
UINotificationFeedbackGenerator available from iOS 10 and work with Haptic v2, we can check this:
let feedbackSupportLevel = UIDevice.current.value(forKey: "_feedbackSupportLevel") as? Int
if #available(iOS 10.0, *), let feedbackSupportLevel = feedbackSupportLevel, feedbackSupportLevel > 1 {
do { // 1
let generator = UIImpactFeedbackGenerator(style: .medium)
generator.impactOccurred()
}
do { // or 2
let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(.success)
}
} else {
AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
}