iosswiftswift3appdelegateshake

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.


Solution

  • 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 for later versions this does not seem to work anymore. You need to add the above code in your view controller instead