//震动一次
/// 震动 OC代码 + (void)impactOccurred { UIImpactFeedbackGenerator *feedBackGenertor = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium]; [feedBackGenertor impactOccurred]; }
持续震动
///震动两秒,间隔0.1秒震动一次 startContinuousVibration(duration: 2, interval: 0.1) /// 持续多长时间的震动 /// - Parameters: /// - duration: 持续多长时间的震动 /// - interval: 每次震动的间隔 private func startContinuousVibration(duration: TimeInterval, interval: TimeInterval ) { let feedbackGenerator = UIImpactFeedbackGenerator(style: .medium) feedbackGenerator.prepare() // 预先准备反馈生成器 // 持续两秒的震动,定期触发反馈 // let duration: TimeInterval = 2.0 // let interval: TimeInterval = 0.1 // 每次震动的间隔 // 每隔 interval 秒触发一次震动,直到达到 2 秒 DispatchQueue.main.async { self.triggerVibrationRepeatedly(with: feedbackGenerator, interval: interval, duration: duration, elapsedTime: 0.0) } } private func triggerVibrationRepeatedly(with generator: UIImpactFeedbackGenerator, interval: TimeInterval, duration: TimeInterval, elapsedTime: TimeInterval) { // 每隔 interval 秒触发一次震动 if elapsedTime < duration { generator.impactOccurred() let newElapsedTime = elapsedTime + interval // 递归调用自己,直到达到持续时间 DispatchQueue.main.asyncAfter(deadline: .now() + interval) { self.triggerVibrationRepeatedly(with: generator, interval: interval, duration: duration, elapsedTime: newElapsedTime) } } }
import AudioToolbox ///震动两秒 间隔震动 private func startVibration() { let vibrationTime: TimeInterval = 2.0 // 震动的持续时间 // 开始震动 AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) // 延时停止震动 DispatchQueue.main.asyncAfter(deadline: .now() + vibrationTime) { // 停止震动 AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) } }