Thursday, November 5, 2009

iPhone: Shake to Update

Many applications perform some basic functions(like updating the UI, playing a sound etc.) when user shakes the iphone. Following snippet shows how to add this functionality in your app:

//In the .h file add the like this:
@interface TableViewController : UIViewController
//Add these two variables in the .h
BOOL shakeDetected;
UIAcceleration* lastAcceleration;
//Create a property
@property (retain) UIAcceleration* lastAcceleration;

//In the .m synthesize your property
@synthesize lastAcceleration;


//In the .m file, in your viewdidload add this line
[UIAccelerometer sharedAccelerometer].delegate = self;

//Add this method to the .m file
//Shake Detection Part 1
static BOOL IsDeviceShaking(UIAcceleration* last, UIAcceleration* current, double threshold) {
double deltaX = fabs(last.x - current.x);
double deltaY = fabs(last.y - current.y);
double deltaZ = fabs(last.z - current.z);
return (deltaX > threshold && deltaY > threshold) ||
(deltaX > threshold && deltaZ > threshold) ||
(deltaY > threshold && deltaZ > threshold);
}

//And add this method to the .m file also
//Shake Detection Part 2
- (void) accelerometer: (UIAccelerometer *)accelerometer didAccelerate: (UIAcceleration *)acceleration {
if (self.lastAcceleration) {
if (!shakeDetected && IsDeviceShaking(self.lastAcceleration, acceleration, 0.7)) {
shakeDetected = YES;
//This is where you put what you want to happen when it shakes
//The line below reloads the table
[tableView reload];
}
else if (shakeDetected && !IsDeviceShaking(self.lastAcceleration, acceleration, 0.2)) {
shakeDetected = NO;
}
}
self.lastAcceleration = acceleration;
}