• Latest News

    Powered by Blogger.
    Saturday, April 26, 2014

    iOS - Accelerometer


    iOS Accelerometer

    Introduction

    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 ground. For testing this example you'll need it run it on device and it doesn't work on simulator.

    Steps Involved

    1. Create a simple View based application.
    2. Add three labels in ViewController.xib and create ibOutlets naming them as xlabel, ylabel and zlabel.
    3. Update ViewController.h as follows.
    #import <UIKit/UIKit.h>
    
    @interface ViewController : UIViewController<UIAccelerometerDelegate>
    {
        IBOutlet UILabel *xlabel;
        IBOutlet UILabel *ylabel;
        IBOutlet UILabel *zlabel;
    
    }
    @end
    
    
    
    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
    

    iOS Tutorial

    OutputNow when we run the application in iPhone device we'll get the following output.


                                   

    • Blogger Comments
    • Facebook Comments

    0 comments:

    Post a Comment

    Item Reviewed: iOS - Accelerometer Rating: 5 Reviewed By: Unknown
    Scroll to Top