简体   繁体   English

如何使用 Swift 让 iPhone 振动?

[英]How to make iPhone vibrate using Swift?

I need to make the iPhone vibrate, but I don't know how to do that in Swift.我需要让 iPhone 振动,但我不知道如何在 Swift 中做到这一点。 I know that in Objective-C, you just write:我知道在 Objective-C 中,你只需写:

import AudioToolbox
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);

But that is not working for me.但这对我不起作用。

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.您可以根据需要将其放入函数或 IBAction 中。

Code Update:代码更新:

 AudioServicesPlayAlertSoundWithCompletion(SystemSoundID(kSystemSoundID_Vibrate)) { }

As apple code docs written:正如苹果代码文档所写:

This function will be deprecated in a future release.此功能将在未来版本中弃用。 Use AudioServicesPlaySystemSoundWithCompletion instead.请改用 AudioServicesPlaySystemSoundWithCompletion。

NOTE: If vibrate doesn't work.注意:如果振动不起作用。 check vibrate is enable in sounds and haptics settings检查振动是否在声音和触觉设置中启用

In iOS 10 on iPhone 7 or 7 Plus, try:在 iPhone 7 或 7 Plus 上的 iOS 10 中,尝试:

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

Swift 4.2 Updated斯威夫特 4.2 更新

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

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/更多关于振动 - http://www.mikitamanko.com/blog/2017/01/29/haptic-feedback-with-uifeedbackgenerator/

For iOS 10.0+ You can try UIFeedbackGenerator对于iOS 10.0+你可以试试UIFeedbackGenerator

Simple viewController above, just replace your view controller in your test "single view app"上面的简单 viewController,只需在您的测试“单视图应用程序”中替换您的视图控制器

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

Swift 4.2, 5.0斯威夫特 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

We can do this in Xcode7.1我们可以在 Xcode7.1 中做到这一点

import UIKit
import AudioToolbox


class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        AudioServicesPlayAlertSound(kSystemSoundID_Vibrate)
    }
}

You can vibrate the phone using either AudioServices or Haptic Feedback .您可以使用AudioServicesHaptic 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.查看我的开源框架Haptica ,它同时支持Haptic FeedbackAudioServices和独特的振动模式。 Works on Swift 4.2, Xcode 10适用于 Swift 4.2、Xcode 10

import AudioToolbox

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

Now you can just call UIDevice.vibrate() as needed.现在您可以根据需要调用UIDevice.vibrate()

UINotificationFeedbackGenerator available from iOS 10 and work with Haptic v2, we can check this: UINotificationFeedbackGenerator 可从 iOS 10 使用并与 Haptic v2 一起使用,我们可以检查:

  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))
        }
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))

Here you will find all codes for each .caf and associated category : 在这里,您将找到每个.caf和相关类别的所有代码:

https://github.com/TUNER88/iOSSystemSoundsLibrary https://github.com/TUNER88/iOSSystemSoundsLibrary

For example if you want a lighter vibration you can use the code 1003. 例如,如果您想要更轻的振动,可以使用代码1003。

Good luck and have fun ;) 祝好运并玩得开心点 ;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM