iPhone
motion detection
shake gesture
iOS development
mobile sensors

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

  1. motionBegan(_:with:):
    • This method is invoked when the system detects that a shake motion has started.
    • Example:
swift
1    override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
2        if motion == .motionShake {
3            print("Shake started.")
4            // Implement code to respond to the shake starting.
5        }
6    }
  1. 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:
swift
1    override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
2        if motion == .motionShake {
3            print("Shake ended.")
4            // Insert logic to respond when the shake ends.
5        }
6    }
  1. motionCancelled(_:with:):
    • Invoked when the shake motion is interrupted, for example, by an incoming phone call.
    • Example:
swift
1    override func motionCancelled(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
2        if motion == .motionShake {
3            print("Shake cancelled.")
4            // Handle any cleanup here.
5        }
6    }

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.

swift
1override var canBecomeFirstResponder: Bool {
2    return true
3}
4
5override func viewDidAppear(_ animated: Bool) {
6    super.viewDidAppear(animated)
7    becomeFirstResponder()
8}
9
10override func viewWillDisappear(_ animated: Bool) {
11    super.viewWillDisappear(animated)
12    resignFirstResponder()
13}

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.

swift
1import CoreMotion
2
3let motionManager = CMMotionManager()
4
5func startAccelerometerUpdates() {
6    motionManager.accelerometerUpdateInterval = 0.2
7    motionManager.startAccelerometerUpdates(to: OperationQueue.main) { (data, error) in
8        guard let accelerometerData = data else { return }
9        let acceleration = accelerometerData.acceleration
10        let magnitude = sqrt((acceleration.x * acceleration.x) +
11                             (acceleration.y * acceleration.y) +
12                             (acceleration.z * acceleration.z))
13        if magnitude > 2.5 {
14            print("Custom shake detected.")
15            // Custom shake logic
16        }
17    }
18}

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:

FeatureDescription
motionBeganDetects the start of a shake motion.
motionEndedDetects the end of a shake motion, ideal for triggering actions.
motionCancelledInvoked when a shake is interrupted.
Custom Shake SensitivityAchieved using Core Motion to set a custom threshold for detecting shakes.
becomeFirstResponder MethodMust 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.


Course illustration
Course illustration

All Rights Reserved.