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.
iphone development 























