How to Use Sensors in the iOS Framework

By Rajiv Ramnath

Sensors in the iOS framework operate at two layers of abstraction. At the lowest level of abstraction are the base sensors, such as the acceleration sensor (or accelerometer) and the temperature sensor, that return the actual sensed values. The accelerometer returns the raw values of acceleration in three dimensions.

At the next level of abstraction are virtual sensors that interpret raw sensor values returned by the other sensors to provide a higher-order value. An example of such a sensor is the orientation sensor, which interprets the raw values of acceleration in the three dimensions to figure out orientation changes.

Because the acceleration sensor interprets the raw values of acceleration in three dimensions to figure out orientation changes, the orientation sensor is considered a high-order sensor.

As with all sensors, the orientation sensor must be started from your code before it will return any values. Once it’s running, the orientation sensor starts sending changes in orientation to your app. To help you understand how this happens, examine the ViewDidLoad method of the Sensor view controller. Below is the relevant extract from this method:

- (void)viewDidLoad{
 // start listening for orientation changes
 [[NSNotificationCenter defaultCenter]
 [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

In the preceding code, the Sensor view controller adds itself as an observer to the device’s notification manager and registers to observe orientation change events. Then the method call to [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications] starts the process of monitoring the orientation.

Orientation change events are caught and saved by the orientationChanged method shown here:

- (void) orientationChanged: (NSNotification *) orientationNotification {
 deviceOrientation = [[UIDevice currentDevice] orientation];

Finally, getOrientation can be used to read the saved orientation and display it appropriately. Here’s the code for getOrientation:

- (IBAction) getOrientation:(id)sender{
 NSString *orientationString=nil;
 switch (deviceOrientation){
  case UIDeviceOrientationUnknown:
   orientationString = @"Unknown";
  case UIDeviceOrientationPortrait:
   orientationString = @"Portrait";
  case UIDeviceOrientationPortraitUpsideDown:
   orientationString = @"Portrait Upside Down";
  case UIDeviceOrientationLandscapeLeft:
   orientationString = @"Landscape Left";
  case UIDeviceOrientationLandscapeRight:
   orientationString = @"Landscape Right";
  case UIDeviceOrientationFaceUp:
   orientationString = @"Face Up";
  case UIDeviceOrientationFaceDown:
   orientationString = @"Face Down";
   orientationString = @"Unknown";
 [orientationTextView setText:orientationString];