Liran Cohen
Liran Cohen

Reputation: 194

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.

Upvotes: 12

Views: 8175

Answers (3)

Rashwan L
Rashwan L

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

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

Upvotes: 8

spnkr
spnkr

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

jk2K
jk2K

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

Related Questions