Detect shake gesture in Swift

von tobonaut

In my opinion, one of the most underrated iOS gesture is the shake’y one. To shake your phone is a natural hand movement. As I was young, the dictum „Shake to {verb}“ was very common. iOS makes it unbelievable easy to listen or react to this event. I used this to implement Nomster’s „Shake to decide“-feature.

I used the built in event handler motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) of iOS 2 and later (Apple Developer reference). This method will be raised in case of a detected motion has ended. We can identify the type of the gesture by using the enum UIEventSubtype values. The method is inherited by the NSObject.

After this two lines of code, you can add any additional control flow you want to this method. In case of Nomster, I put a simple random bot into it.

override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {
        if motion == .MotionShake {
            // Do what you want

If you have multiple respond-able classes, you have to override the method:

override func canBecomeFirstResponder() -> Bool {
    return true

You can see the code in action in Nomster’s ’shake to decide‘-feature. Related file: DiceViewController.swift