Listen to all touch events in an iOS app
You need a subclass of UIApplication
(let's call it MyApplication
).
You modify your main.m
to use it:
return UIApplicationMain(argc, argv, @"MyApplication", @"MyApplicationDelegate");
And you override the method [MyApplication sendEvent:]
:
- (void)sendEvent:(UIEvent*)event { //handle the event (you will probably just reset a timer) [super sendEvent:event];}
A subclass of UIWindow
could be used to do this, by overriding hitTest:
. Then in the XIB of your main window, there is an object usually simply called Window
. Click that, then on the right in the Utilities pane go to the Identities (Alt-Command-3). In the Class text field, enter the name of your UIWindow
subclass.
MyWindow.h
@interface MyWindow : UIWindow@end
MyWindow.m
@implementation MyWindow- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{ UIView *res; res = [super hitTest:point withEvent:event]; // Setup/reset your timer or whatever your want to do. // This method will be called for every touch down, // but not for subsequent events like swiping/dragging. // Still, might be good enough if you want to measure // in minutes. return res;} @end
You can use a tap gesture recognizer for this. Subclass UITapGestureRecognizer
and import <UIKit/UIGestureRecognizerSubclass.h>
. This defines touchesBegan:
, touchesMoved:
, touchesEnded:
and touchesCancelled:
. Put your touch-handling code in the appropriate methods.
Instantiate the gesture recognizer in application:didFinishLaunchingWithOptions:
and add it to UIWindow
. Set cancelsTouchesInView
to NO
and it'll pass all touches through transparently.
Credit: this post.