iOS Accelerometer Sensor (Accelerometer)
Introduction
The accelerometer detects changes in the device's position along the x, y, and z axes.
Using the accelerometer, you can determine the device's current position relative to the ground.
The following example code needs to be run on a real device; it will not work on a simulator.
Example Steps
- Create a simple view application.
- Add three labels in ViewController.xib and create ibOutlets for them: xlabel, ylabel, and zlabel.
Update ViewController.h as shown below:
#import <UIKit/UIKit.h> @interface ViewController : UIViewController<UIAccelerometerDelegate> { IBOutlet UILabel *xlabel; IBOutlet UILabel *ylabel; IBOutlet UILabel *zlabel; } @end
Update ViewController.m as shown below:
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [[UIAccelerometer sharedAccelerometer]setDelegate:self]; // Do any additional setup after loading the view, typically from a nib } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate: (UIAcceleration *)acceleration{ [xlabel setText:[NSString stringWithFormat:@"%f", acceleration.x]]; [ylabel setText:[NSString stringWithFormat:@"%f", acceleration.y]]; [zlabel setText:[NSString stringWithFormat:@"%f", acceleration.z]]; } @end
Output
When we run this application on an iPhone device, the output will be as shown below.