iOS (iPhone, iPad) Tutorial on iOS Accelerometer

accelerometer is used for detecting the changes in the position of the device in the three directions x, y and z. we can know the current position of the device relative to the ground. for testing this example, you'll need to run it on a device and to doesn't work on simulator.

accelerometer – steps involved

step 1 − create a simple view based application.

step 2 − add three labels in viewcontroller.xib and create iboutlets naming them as xlabel, ylabel, and zlabel.

step 3 − update viewcontroller.h as follows −

#import <uikit/uikit.h>

@interface viewcontroller : uiviewcontroller<uiaccelerometerdelegate> {
   iboutlet uilabel *xlabel;
   iboutlet uilabel *ylabel;
   iboutlet uilabel *zlabel;
}
@end

step 4 − update viewcontroller.m as follows −

#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 in iphone device, we'll get the following output −

ios tutorial