UIAccelerometer* accelerometer = [UIAccelerometer sharedAccelerometer];
This code above shows how to get the accelerometer instance in the code.The following line sets up the update interval:
[accelerometer setUpdateInterval: 1.0 / 10.0f];
[accelerometer setDelegate:self];
each 0.1 second the accelerometer will update the program that implements delegate method:
- (void)accelerometer:(UIAccelerometer *)acel didAccelerate:(UIAcceleration *)aceler
{
NSLog(@"acceleration.x = %+.6f", aceler.x);
NSLog(@"acceleration.y = %+.6f", aceler.y);
NSLog(@"acceleration.z = %+.6f", aceler.z);
}
Do not forget to add UIAccelerometerDelegate, for example, to a view controller class:
@interface ViewController : UIViewController <UIAccelerometerDelegate>
So here is the step-by-step scenario for beginners:
1. Create new Single-View project in Xcode.
2. In ViewController.h file add <UIAccelerometerDelegate> after UIViewController.
3. In ViewController.m file, modify viewDidLoad method:
- (void)viewDidLoad
{
[super viewDidLoad];
UIAccelerometer* accelerometer = [UIAccelerometer sharedAccelerometer];
[accelerometer setUpdateInterval: 1.0 / 10.0f];
[accelerometer setDelegate:self];
}
4. In ViewController.m file, add new method:
- (void)accelerometer:(UIAccelerometer *)acel didAccelerate:(UIAcceleration *)aceler
{
NSLog(@"acceleration.x = %+.6f", aceler.x);
NSLog(@"acceleration.y = %+.6f", aceler.y);
NSLog(@"acceleration.z = %+.6f", aceler.z);
}
This program works on iPhone. It does not make much sense to test it simulator.
No comments:
Post a Comment