Saturday, May 25, 2013

UIApplication sendEvent example in Objective C (iOS)


[UIApplication sendEvent]

Dispatches an event to the appropriate responder objects in the application.
- (void)sendEvent:(UIEvent *)event
Parameters
event
UIEvent object encapsulating the information about an event, including the touches involved.
Discussion of [UIApplication sendEvent]
Subclasses may override this method to intercept incoming events. Any intercepted events should be dispatched by calling [super sendEvent:event] after examining the intercepted event.
Example of [UIApplication sendEvent]
- (void)sendEvent:(UIEvent *)event {
  [super sendEvent:event];
  [self. idleTimer invalidate];
  self. idleTimer = [NSTimer scheduledTimerWithTimeInterval:kIDLE_TIME target:self selector:@selector(logout:) userInfo:nil repeats:NO];}
Example of [UIApplication sendEvent]
@interface YourWindow : UIWindow {
    NSDate timeOfLastTouch;
}
@end

@implementation YourWindow

- (void)sendEvent:(UIEvent *)event
{
    if(<acceptible last touch>)
        timeOfLastTouch = <current time>;

    [super sendEvent:event];
}

@end
Example of [UIApplication sendEvent]
- (void)sendEvent:(UIEvent *)event {
    [super sendEvent:event];

    // Only want to reset the timer on a Began touch or an Ended touch, to reduce the number of timer resets.
    NSSet *allTouches = [event allTouches];
    if ([allTouches count] > 0) {
        // allTouches count only ever seems to be 1, so anyObject works here.
        UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase;
        if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded)
            [self resetIdleTimer];
    }
}

- (void)resetIdleTimer {
    if (idleTimer) {
        [idleTimer invalidate];
        [idleTimer release];
    }

    idleTimer = [[NSTimer scheduledTimerWithTimeInterval:maxIdleTime target:self selector:@selector(idleTimerExceeded) userInfo:nil repeats:NO] retain];
}

- (void)idleTimerExceeded {
    NSLog(@"idle time exceeded");
}