【问题标题】:How to make my iphone vibrate twice when I click on a button?当我点击一个按钮时,如何让我的iphone振动两次?
【发布时间】:2015-04-24 05:00:40
【问题描述】:

当我点击一个按钮时,我会搜索让我的 iPhone 振动两次(比如短信提醒振动)

AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) 我只获得了一次正常振动,但我想要两条短裤:/。

【问题讨论】:

标签: ios swift iphone-vibrate


【解决方案1】:

iOS 10 更新

在 iOS 10 中,有一些新方法可以用最少的代码做到这一点。

方法 1 - UIImpactFeedbackGenerator:

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

方法 2 - UINotificationFeedbackGenerator:

let feedbackGenerator = UINotificationFeedbackGenerator()
feedbackGenerator.notificationOccurred(.error)

方法 3 - UISelectionFeedbackGenerator:

let feedbackGenerator = UISelectionFeedbackGenerator()
feedbackGenerator.selectionChanged()

【讨论】:

  • UINotificationGenerator 仅适用于具有 Taptic Engine 的设备。那是 iPhone 7 及更新版本。我在我的 iPhone 6s 上试过这个代码,没有用。我阅读了更多关于它的内容,发现它仅适用于具有 Taptic Engine 并且系统触觉设置必须在系统设置中启用的设备,否则它将无法工作。跨度>
  • 在 webrtc 调用兄弟时不工作,不要。知道为什么
【解决方案2】:
#import <AudioToolbox/AudioServices.h>


AudioServicesPlayAlertSound(UInt32(kSystemSoundID_Vibrate))

这是swift函数……详细说明见this文章。

【讨论】:

  • 这对我不起作用,也许苹果改变了一些东西,或者我做错了什么?它只给我一个振动。
【解决方案3】:

这是我想出的:

import UIKit
import AudioToolbox

class ViewController: UIViewController {

    var counter = 0
    var timer : NSTimer?

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func vibratePhone() {
        counter++
        switch counter {
        case 1, 2:
            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
        default:
            timer?.invalidate()
        }
    }

    @IBAction func vibrate(sender: UIButton) {
        counter = 0
        timer = NSTimer.scheduledTimerWithTimeInterval(0.6, target: self, selector: "vibratePhone", userInfo: nil, repeats: true)
    }
}

当您按下按钮时,计时器将启动并以所需的时间间隔重复。 NSTimer 调用 vibratePhone(Void) 函数,从那里我可以控制手机振动的次数。在这种情况下,我使用了开关,但您也可以使用 if else。只需在每次调用函数时设置一个计数器即可。

【讨论】:

  • 这行得通,但是在第一次振动之前有一个延迟大约一秒钟。
【解决方案4】:

如果您只想振动两次。你可以..

    func vibrate() {
        AudioServicesPlaySystemSoundWithCompletion(kSystemSoundID_Vibrate) {
            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
        }
    }

通过使用递归和AudioServicesPlaySystemSoundWithCompletion,可以实现多次振动。

您可以将计数传递给振动功能,例如vibrate(count: 10)。然后它会振动 10 次。

    func vibrate(count: Int) {
        if count == 0 {
            return
        }
        AudioServicesPlaySystemSoundWithCompletion(kSystemSoundID_Vibrate) { [weak self] in
            self?.vibrate(count: count - 1)
        }
    }


如果使用UIFeedbackGenerator,有一个很棒的库Haptica


希望对你有帮助。

【讨论】:

  • 当你播放音频或 webrtc 调用时,只有 UIFeedbackGenerator 工作
猜你喜欢
  • 2021-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多