Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting shake in AppDelegate

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.

like image 759
Liran Cohen Avatar asked Jan 13 '16 17:01

Liran Cohen


2 Answers

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")
        }
    }
}
like image 196
jk2K Avatar answered Oct 02 '22 00:10

jk2K


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")
    }
}

As for later versions this does not seem to work anymore. You need to add the above code in your view controller instead

like image 41
Rashwan L Avatar answered Oct 02 '22 00:10

Rashwan L