HOWTO: Long press with KIF

If you are using KIF as a testing framework for your iOS application and you need to perform a long press, you have to write your own method or step as it is not included in the source as of this writing. As it turns out the solution is quite simple - tap at a point, wait for a certain timeout, and release the tap.

To implement this behavior, we are going to modify one of KIF's files. In particular, "KIF/Additions/UIView-KIFAdditions.m". At the end of the file, add the following code:

- (void)longTapAtPoint:(CGPoint)point withDelay:(NSInteger)delay andCompletion:(void(^)(void)) completion;
    // Handle touches in the normal way for other views
    UITouch *touch = [[UITouch alloc] initAtPoint:point inView:self];
    [touch setPhase:UITouchPhaseBegan];
    // Create the touch event and send it to the application
    UIEvent *event = [self _eventWithTouch:touch];
    [[UIApplication sharedApplication] sendEvent:event];
    // Perform long touch
    dispatch_after( dispatch_time( DISPATCH_TIME_NOW, NSEC_PER_SEC * delay), dispatch_get_current_queue(), ^(void){
	[touch setPhase:UITouchPhaseEnded];
	[[UIApplication sharedApplication] sendEvent:event];
	// Dispatching the event doesn't actually update the first responder, so fake it
	if ([touch.view isDescendantOfView:self] && [self canBecomeFirstResponder]) {
		[self becomeFirstResponder];
	if (completion) completion();
    // Release the touch
    [touch release];

That was easy, right?

As always, comments and questions are always welcomed!