- iOS Tutorial
- iOS - Home
- iOS - Getting Started
- iOS - Environment Setup
- iOS - Objective-C Basics
- iOS - First iPhone Application
- iOS - Actions and Outlets
- iOS - Delegates
- iOS - UI Elements
- iOS - Accelerometer
- iOS - Universal Applications
- iOS - Camera Management
- iOS - Location Handling
- iOS - SQLite Database
- iOS - Sending Email
- iOS - Audio & Video
- iOS - File Handling
- iOS - Accessing Maps
- iOS - In-App Purchase
- iOS - iAd Integration
- iOS - GameKit
- iOS - Storyboards
- iOS - Auto Layouts
- iOS - Twitter & Facebook
- iOS - Memory Management
- iOS - Application Debugging
- iOS Useful Resources
- iOS - Quick Guide
- iOS - Useful Resources
- iOS - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
Advertisements