How to make iPhone vibrate using Swift?

IosIphoneSwiftVibration

Ios Problem Overview


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
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);

But that is not working for me.

Ios Solutions


Solution 1 - Ios

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

Solution 2 - Ios

In iOS 10 on iPhone 7 or 7 Plus, try:

let generator = UIImpactFeedbackGenerator(style: .heavy)
generator.impactOccurred()

Solution 3 - Ios

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))
            }
        }
    }

Solution 4 - Ios

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/

Solution 5 - Ios

Swift 4.2, 5.0

 if #available(iOS 10.0, *) {
      UIImpactFeedbackGenerator(style: .light).impactOccurred()
   } 

You can also choose other styles like

    style: .heavy
    style: .medium

    //Note: soft and rigid available in only iOS 13.0
    style: .soft
    style: .rigid

Solution 6 - Ios

For iOS 10.0+ You can try UIFeedbackGenerator

Simple viewController above, just replace your view controller in your test "single view app"

import UIKit

class ViewController: UIViewController {

    var i = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let btn = UIButton()
        self.view.addSubview(btn)
        btn.translatesAutoresizingMaskIntoConstraints = false
        
        btn.widthAnchor.constraint(equalToConstant: 160).isActive = true
        btn.heightAnchor.constraint(equalToConstant: 160).isActive = true
        btn.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        btn.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        
        btn.setTitle("Tap me!", for: .normal)
        btn.setTitleColor(UIColor.red, for: .normal)
        btn.addTarget(self, action: #selector(tapped), for: .touchUpInside)
    }
    
    @objc func tapped() {
        i += 1
        print("Running \(i)")
        
        switch i {
        case 1:
            let generator = UINotificationFeedbackGenerator()
            generator.notificationOccurred(.error)
            
        case 2:
            let generator = UINotificationFeedbackGenerator()
            generator.notificationOccurred(.success)
            
        case 3:
            let generator = UINotificationFeedbackGenerator()
            generator.notificationOccurred(.warning)
            
        case 4:
            let generator = UIImpactFeedbackGenerator(style: .light)
            generator.impactOccurred()
        case 5:
            let generator = UIImpactFeedbackGenerator(style: .medium)
            generator.impactOccurred()
            
        case 6:
            let generator = UIImpactFeedbackGenerator(style: .heavy)
            generator.impactOccurred()

        default:
            let generator = UISelectionFeedbackGenerator()
            generator.selectionChanged()
            i = 0
        }
    }
}

Solution 7 - Ios

We can do this in Xcode7.1

import UIKit
import AudioToolbox


class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        AudioServicesPlayAlertSound(kSystemSoundID_Vibrate)
    }
}

Solution 8 - Ios

You can vibrate the phone using either AudioServices or Haptic Feedback.

// AudioServices
AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))

// Haptic Feedback
UIImpactFeedbackGenerator(style: .medium).impactOccurred()

Checkout my open source framework Haptica, it supports both Haptic Feedback, AudioServices and unique vibrations patterns. Works on Swift 4.2, Xcode 10

Solution 9 - Ios

import AudioToolbox

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

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

Solution 10 - Ios

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))
        }

Solution 11 - Ios

AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNico GutraichView Question on Stackoverflow
Solution 1 - IosSteve RosenbergView Answer on Stackoverflow
Solution 2 - IosAdam SmakaView Answer on Stackoverflow
Solution 3 - IosmuhasturkView Answer on Stackoverflow
Solution 4 - IosMichaelView Answer on Stackoverflow
Solution 5 - IosRashid LatifView Answer on Stackoverflow
Solution 6 - IosKiryl BelasheuskiView Answer on Stackoverflow
Solution 7 - Iosken0nekView Answer on Stackoverflow
Solution 8 - IosefremidzeView Answer on Stackoverflow
Solution 9 - IosMohammad RazipourView Answer on Stackoverflow
Solution 10 - IosSergei LysiukView Answer on Stackoverflow
Solution 11 - IosDhaval H. NenaView Answer on Stackoverflow