Search code examples
iphoneobjective-ciosaccelerometer

How to call accelerator method using IBAction method?


I want to add a start button which will start the accelerometer, how can I set an IBAction to do that, in my code I use:

-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
    x.text = [NSString stringWithFormat:@"X is: %f", acceleration.x];
    y.text = [NSString stringWithFormat:@"Y is: %f", acceleration.y];
    z.text = [NSString stringWithFormat:@"Z is: %f", acceleration.z];
NSLog (@"Y = @%f", y.text);
}

-(IBAction)startPedometerPressed {
    [startButton accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration];

}

This returns an error because of the undeclared identifier 'accelerometer'.

I'm sure there is something wrong in how I call the method but not sure what is it!


Solution

  • you have to write your accelerometer initialization code in the IBAction function. remove it from ViewDidLoad. now accelerometer works after the button pressed.

    -(IBAction)startPedometerPressed 
    {
         [[UIAccelerometer sharedAccelerometer] setUpdateInterval:(1.0 / kAccelerometerFrequency)];
         [[UIAccelerometer sharedAccelerometer] setDelegate:self];
    }
    

    Hope this helps.