Hello World!
I'm a Developer at Master of Malt, a University of Brighton graduate, a 1st Kyu in Kyokushinkai Karate, a video gamer and technology enthusiast. Read more about me over here.
CloudANDTidus
Search
Gaming With Lemons
Games


« You know, Chevy Chase woke up one day and just wasn't funny anymore | Main | I’ve done everything the Bible says - even the stuff that contradicts the other stuff! »
Monday
Jan092012

Intercepting iPhone/iPad keyboard events

So a problem; you have a web app running on iOS that you want to receive keyboard events at any time. The simplest solution would be to make the user put focus on a designated text field that you could watch for keyboard events in JavaScript, however it's a pain in the arse if the user has to keep putting focus back when they loose it. Unfortunately the app itself can't force focus on the text field as mobile safari blocks it (only a touch event triggered by the user will bring up the keyboard). 

The solution, as crazy as it sounds, is to create a native iOS wrapper app that can monitor keyboard events at all times and forward them onto the web app. To do so all you need to do is create is a view controller that displays a UIWebView with your web app inside and implement the UIKeyInput protocol

@interface ViewController : UIViewController <UIKeyInput>

In the implementation of your view controller you just need a few of methods.

- (void) insertText:(NSString* )text
{
    NSLog(@"%@", text);
}

- (void)deleteBackward { }

- (BOOL) canBecomeFirstResponder
{
    return YES;
}

- (BOOL) resignFirstResponder
{
    return NO;
}

- (BOOL) hasText
{
    return YES;
}

Insert text is where we will receive keyboard input and resign first responder is the crucial method that returns false to prevent the web app from taking the keyboard if an element receives focus. Obviously the negative to this is you can never type directly into elements in the web app. 

Once the native app receives keyboard events they can be passed onto the web app using JavaScript. You just need to create a receiving method in the web app and call it in the native app like so.

- (void) insertText:(NSString* )text
{
    NSLog(@"%@", text);
    [myWebView stringByEvaluatingJavaScriptFromString:[NSString 
        stringWithFormat:@"receiveText('%@');", text]];
}

And there you have it, intercepting keyboard events for a web app using a native wrapper.

Reader Comments (1)

Thanx for the piece of code you posted here. Can you tell me what software I need for creating a native iOS wrapper?

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>