How do I detect when someone shakes an iPhone?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Detecting when someone shakes an iPhone is an important functionality for apps that wish to incorporate interactive and intuitive features based on physical user interactions with the device. In iOS development, this capability is provided by the UIKit framework, specifically through subclasses of UIResponder.
Understanding Motion Events in iOS
Motion events in iOS refer to physical movements of the device detected by its onboard accelerometer. These events can be captured to execute specific code, such as undo actions, special animations, or mode switching when the phone is shaken.
To detect a shake in an iPhone app, developers typically override methods in the UIResponder class, which provides fundamental interface behaviors and the event handling system. The key methods to override include:
motionBegan(_:with:)motionEnded(_:with:)motionCancelled(_:with:)
Motion Detection Methods
- motionBegan(_:with:):
- This method is invoked when the system detects that a shake motion has started.
- Example:
- motionEnded(_:with:):
- This method is called when the shaking stops. It's the most useful method for triggering actions based on a completed shake gesture.
- Example:
- motionCancelled(_:with:):
- Invoked when the shake motion is interrupted, for example, by an incoming phone call.
- Example:
Enabling Shake Detection
To enable shake detection in an app, the app's view controller must become the first responder. By default, view controllers can become the first responder, but they need to return true for this capability.
Custom Shake Threshold
Although iOS provides default settings for detecting shakes, developers can add additional layers of detection by directly processing accelerometer data using Core Motion. This customization allows changing sensitivity to shakes by adjusting the threshold of detected motion.
In this example, an arbitrary threshold of 2.5 is set for the acceleration magnitude. This threshold can be fine-tuned based on testing and app requirements.
Summary
Here's a concise summary presented in a table format:
| Feature | Description |
| motionBegan | Detects the start of a shake motion. |
| motionEnded | Detects the end of a shake motion, ideal for triggering actions. |
| motionCancelled | Invoked when a shake is interrupted. |
| Custom Shake Sensitivity | Achieved using Core Motion to set a custom threshold for detecting shakes. |
| becomeFirstResponder Method | Must be called in view controller to allow detection of gestures like shake. |
By properly implementing these methods and configurations, an iOS app can effectively detect shake gestures, thereby enriching user interaction and providing a dynamic experience.

