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.
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.
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")
}
}
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")
}
}
}
open
in front of func for iOS 10.3/Xcode8.3. –
Caudate 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")
}
}
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")
}
}
}
© 2022 - 2024 — McMap. All rights reserved.