在我的物理设备 (iPhone XR) 上测试以下代码时,我没有遇到任何触觉输出。我关注了 Apple Developer 的“播放单击触觉模式”文章,并仔细检查了互联网上的其他各种文章,我确信我已经正确实现了它。此外,运行时没有发现任何错误。我的设备不输出触觉模式的原因可能是什么?
旁注:
- 我可以确认我的手机确实为其他应用程序产生了触觉,所以这似乎不是我的物理设备的问题。
- 我还单独实现了一个 AVAudioPlayer;我怀疑这会干扰,但我想我会提到它以防万一。
任何帮助将不胜感激 - 谢谢!
var hapticEngine: CHHapticEngine!
var hapticPlayer: CHHapticPatternPlayer!
override func viewDidLoad() {
super.viewDidLoad()
// Create and configure a haptic engine.
do {
hapticEngine = try CHHapticEngine()
} catch let error {
fatalError("Engine Creation Error: \(error)")
}
// The reset handler provides an opportunity to restart the engine.
hapticEngine.resetHandler = {
print("Reset Handler: Restarting the engine.")
do {
// Try restarting the engine.
try self.hapticEngine.start()
// Register any custom resources you had registered, using registerAudioResource.
// Recreate all haptic pattern players you had created, using createPlayer.
} catch let error {
fatalError("Failed to restart the engine: \(error.localizedDescription)")
}
}
// The stopped handler alerts engine stoppage.
hapticEngine.stoppedHandler = { reason in
print("Stop Handler: The engine stopped for reason: \(reason.rawValue)")
switch reason {
case .audioSessionInterrupt: print("Audio session interrupt")
case .applicationSuspended: print("Application suspended")
case .idleTimeout: print("Idle timeout")
case .systemError: print("System error")
@unknown default:
print("Unknown error")
}
}
// Create haptic dictionary
let hapticDict = [
CHHapticPattern.Key.pattern: [
[
CHHapticPattern.Key.event: [
CHHapticPattern.Key.eventType: CHHapticEvent.EventType.hapticTransient,
CHHapticPattern.Key.time: 0.001,
CHHapticPattern.Key.eventDuration: 1.0
]
]
]
]
// Create haptic pattern from haptic dictionary, then add it to the haptic player
do {
let pattern = try CHHapticPattern(dictionary: hapticDict)
hapticPlayer = try hapticEngine.makePlayer(with: pattern)
} catch let error {
print("Failed to create hapticPlayer: \(error.localizedDescription)")
}
// ...
}
// ...
func playHaptic() {
//audioPlayer?.play()
// Start Haptic Engine
do {
try hapticEngine.start()
} catch let error {
print("Haptic Engine could not start: \(error.localizedDescription)")
}
// Start Haptic Player
do {
try hapticPlayer.start(atTime: 0.0)
print("Why")
} catch let error {
print("Haptic Player could not start: \(error.localizedDescription)")
}
// Stop Haptic Engine
hapticEngine.stop(completionHandler: nil)
}