Reputation: 194
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.
Upvotes: 12
Views: 8175
Reputation: 38833
Add the following snippet in your AppDelegate
:
override func motionBegan(motion: UIEvent.EventSubtype, 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")
}
}
Upvotes: 8
Reputation: 1362
As of Swift 4 or 5, it's UIEvent.EventSubtype
, not UIEventSubtype
.
Also don't forget to add a call to super.motionEnded(motion, with: event)
. This preserves any motionEnded customizations on your view controllers.
extension UIWindow {
open override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
super.motionEnded(motion, with: event)
if motion == .motionShake {
print("Device shaken")
}
}
}
Upvotes: 0
Reputation: 4527
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")
}
}
}
Upvotes: 32