if you want to know, if somebody shakes the iPhone, the following code might be useful.if you use the motionEvent for shaking (this did not work for me.) then it works first time of view controller opens.you will also need to restore the shaking view first responder status when the other view resigns.

– (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
if ( event.subtype == UIEventSubtypeMotionShake ) {
//Put your code here
}
if ( [super respondsToSelector:@selector(motionEnded:withEvent:)] )
[super motionEnded:motion withEvent:event];
}
– (BOOL)canBecomeFirstResponder { return YES; }
– (void) viewWillAppear:(BOOL)animated {
[shakeView becomeFirstResponder];
[super viewWillAppear:animated];
}
– (void) viewWillDisappear:(BOOL)animated {
[shakeView resignFirstResponder];
[super viewWillDisappear:animated];
}

Instead of this one you can use the following procedure. (I came across forums looking for a “shaking” implementation. millenomi’s answer worked well for me.)

//ShakeViewController.h
static BOOL L0AccelerationIsShaking(UIAcceleration* last, UIAcceleration* current, double threshold) {
double deltaX = fabs(last.x – current.x), deltaY = fabs(last.y – current.y), deltaZ = fabs(last.z – current.z);
return (deltaX > threshold && deltaY > threshold) || (deltaX > threshold && deltaZ > threshold) || (deltaY > threshold && deltaZ > threshold);
}
@interface ShakeViewController : UIViewController <UIAccelerometerDelegate> {

BOOL histeresisExcited;
UIAcceleration* lastAcceleration;
}
@property(retain) UIAcceleration* lastAcceleration;
@end

//ShakeViewController.m
@implementation ShakeViewController
@synthesize lastAcceleration
-(void)viewWillAppear:(BOOL)animated {
// For shake gesture.
[UIAccelerometer sharedAccelerometer].delegate = self;
}
– (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
if (self.lastAcceleration) {
if (!histeresisExcited && L0AccelerationIsShaking(self.lastAcceleration, acceleration, 0.7)) {
histeresisExcited = YES;
/* SHAKE DETECTED. DO HERE WHAT YOU WANT. */
} else if (histeresisExcited && !L0AccelerationIsShaking(self.lastAcceleration, acceleration, 0.2)) {
histeresisExcited = NO;
}
}
self.lastAcceleration = acceleration;
}
@end

Advertisements