IOS acceleration sensor (accelerometer)
IOS acceleration sensor (accelerometer)
Introduction
The acceleration sensor detects changes in the position of the device based on the three directions of x, y and z.
The acceleration sensor can be used to know the current position of the device relative to the ground.
The following example code needs to be run on a real device and will not work on the simulator.
Instance steps
1. Create a simple view application
2. Add three labels to ViewController.xib and create an ibOutlets: xlable, ylabel and zlabel
3. As shown below, update ViewController.h
#import <UIKit/UIKit.h> @interface ViewController : UIViewController<UIAccelerometerDelegate> { IBOutlet UILabel *xlabel; IBOutlet UILabel *ylabel; IBOutlet UILabel *zlabel; } @end
4. As shown below, update ViewController.m
#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 the application on an iPhone device, the output we get is as follows.