简体   繁体   中英

Can I receive shake events in my AppDelegate?

The application delegate is a UIResponder subclass (since Xcode 4.2), so it should be able to receive touch and motion events. I added this in my AppDelegate class but it is not working:

-(BOOL)canBecomeFirstResponder
{
    return YES;
}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (motion == UIEventSubtypeMotionShake) {
        NSLog(@"shake");
    }
}

It does work in view controllers of course, but I want to detect shakes application-wide.

Do this:

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [self becomeFirstResponder];

}
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {

    NSLog(@"motionBegan");

}

-(BOOL)canBecomeFirstResponder {
return YES;
}

I extended UIApplication class and added class reference to main: MyApplication.h

@interface MyApplication : UIApplication

@end

MyApplication.m

@implementation MyApplication

- (void) sendEvent:(UIEvent *)event
{
    if( event && (event.subtype==UIEventSubtypeMotionShake))
    {
        AppDelegate *objAppDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

        [objAppDelegate doWhatEver];
        [super sendEvent:event];
    }
    else
    {
        [super sendEvent:event];
    }
}

@end

And the last step in main.m

int main(int argc, char *argv[])
{
return UIApplicationMain(argc, argv, NSStringFromClass([MyApplication class]), NSStringFromClass([AppDelegate class]));
}

This works in all cases.

As far as I know, it should need to become the first responder for receiving the event. If your app has UINavigationController or UITabController, maybe you can try to receive it there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM