How can I detect a device shake in the AppDelegate (across the entire app) in Swift?
I've found answers that describe how to do so in a view controller, but looking to do so across my app.
If you want to globally detect shake motion, the UIWindow implements UIResponder that can receive shake motion event. You can add the following snippet to AppDelegate
extension UIWindow {
open override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
if motion == .motionShake {
print("Device shaken")
}
}
}
Add the following snippet in your AppDelegate
:
override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent?) {
if motion == .MotionShake {
print("Device shaken")
}
}
Swift 3.0 version:
override func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) {
if motion == .motionShake {
print("Device shaken")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With