iOS : How to detect Shake motion?

ios, shake

Solution

This might help you... https://stackoverflow.com/a/2405692/796103

He says that you should set the `UIApplication`'s `applicationSupportsShakeToEdit` to `YES`. and override 3 methods in your VC:

-(BOOL)canBecomeFirstResponder {
    return YES;
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self becomeFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated {
    [self resignFirstResponder];
    [super viewWillDisappear:animated];
}

The rest of your code is fine. (the `-motionEnded:withEvent:`)

Problem

I added the following code to my appDelegate.m ``` - (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event { } - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event { if (motion == UIEventSubtypeMotionShake ) { // User was shaking the device. Post a notification named "shake". [[NSNotificationCenter defaultCenter] postNotificationName:@"shake" object:self]; } } - (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event { } - (void)shakeSuccess { // do something... } ``` and then I added : ``` - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. // INIT THE BACKGROUND PATH STRING [self refreshFields]; [self.window addSubview:navController.view]; [self.window makeKeyAndVisible]; ***[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shakeSuccess) name:@"shake" object:nil];*** return YES; } ``` When I start my app on my iPhone, the method named "shakeSuccess" doesn't called. What should I do to implement this function in my app? any idea?

Original source

Related problems