Acceleration

Acceleration information can arrive in three ways:

As a prepackaged UIEvent
You can receive a UIEvent notifying you of a predefined gesture performed by accelerating the device. At present, the only such gesture is the user shaking the device.
From the shared UIAccelerometer
You can set yourself as the shared UIAccelerometer’s delegate to receive acceleration notifications in accelerometer:didAccelerate:.
With the Core Motion framework
You instantiate CMMotionManager and then obtain information of a desired type. You can ask for accelerometer information, gyroscope information, or device motion information; device motion is a combination of accelerometer and gyroscope information that accurately describes the device’s orientation in space, and is what you’re most likely to want.

Shake Events

A shake event is a UIEvent (Chapter 18). Receiving shake events is rather like receiving remote events (Chapter 27), involving the notion of the first responder. To receive shake events, your app must contain a UIResponder which:

  • Returns YES from canBecomeFirstResponder
  • Is in fact first responder

This responder, or a UIResponder further up the responder chain, should implement some or all of these methods:

motionBegan:withEvent:
Something has started to happen that might or might not turn out to be a shake.
motionEnded:withEvent:
The motion reported in motionBegan:withEvent: is over and has turned out to be a shake.
motionCancelled:withEvent:
The motion reported in motionBegan:withEvent: ...

Get Programming iOS 4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.