简体   繁体   中英

Vibrate indefinitely in Swift

How can I make an iPhone vibrate indefinitely? I know I can do this:

while true {
    AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
}

Is there any way to play the vibration for a certain number of seconds, or something with a similar result that is cleaner? Also, is there a way to make the vibration more intense?

I think you should use Timer .

var timer: Timer?
var numberRepeat = 0
var maxNumberRepeat = 20

func startTimer() {
    //
    timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(self.timerHandler), userInfo: nil, repeats: true)
}

func stopTimer() {
    timer?.invalidate()
    timer = nil
}

@objc func timerHandler() {
    if numberRepeat <= maxNumberRepeat {
        numberRepeat += 1
        vibrateDevice()
    } else {
        stopTimer()
    }
}

func vibrateDevice() {
    AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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