Receive iPhone keyboard events - iphone

Is there anyway to trap all keyboard events across my application? I need to know if user is entering anything using keyboard across my application (Application has multiple views). I was able to capture touchEvents by subclassing UIWindow but unable to capture keyboard events.

Use NSNotificationCenter
[[NSNotificationCenter defaultCenter] addObserver: self selector: #selector(keyPressed:) name: UITextFieldTextDidChangeNotification object: nil];
[[NSNotificationCenter defaultCenter] addObserver: self selector: #selector(keyPressed:) name: UITextViewTextDidChangeNotification object: nil];
........
-(void) keyPressed: (NSNotification*) notification
{
NSLog([[notification object]text]);
}

I wrote about catching events using a little hack of UIEvent in my Blog
Please refer to :
Catching Keyboard Events in iOS for details.
From the above mentioned blog:
The trick is in accessing GSEventKey struct memory directly and check
certain bytes to know the keycode and flags of the key pressed. Below
code is almost self explanatory and should be put in your
UIApplication subclass.
#define GSEVENT_TYPE 2
#define GSEVENT_FLAGS 12
#define GSEVENTKEY_KEYCODE 15
#define GSEVENT_TYPE_KEYUP 11
NSString *const GSEventKeyUpNotification = #"GSEventKeyUpHackNotification";
- (void)sendEvent:(UIEvent *)event
{
[super sendEvent:event];
if ([event respondsToSelector:#selector(_gsEvent)]) {
// Key events come in form of UIInternalEvents.
// They contain a GSEvent object which contains
// a GSEventRecord among other things
int *eventMem;
eventMem = (int *)[event performSelector:#selector(_gsEvent)];
if (eventMem) {
// So far we got a GSEvent :)
int eventType = eventMem[GSEVENT_TYPE];
if (eventType == GSEVENT_TYPE_KEYUP) {
// Now we got a GSEventKey!
// Read flags from GSEvent
int eventFlags = eventMem[GSEVENT_FLAGS];
if (eventFlags) {
// This example post notifications only when
// pressed key has Shift, Ctrl, Cmd or Alt flags
// Read keycode from GSEventKey
int tmp = eventMem[GSEVENTKEY_KEYCODE];
UniChar *keycode = (UniChar *)&tmp;
// Post notification
NSDictionary *inf;
inf = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithShort:keycode[0]],
#"keycode",
[NSNumber numberWithInt:eventFlags],
#"eventFlags",
nil];
[[NSNotificationCenter defaultCenter]
postNotificationName:GSEventKeyUpNotification
object:nil
userInfo:userInfo];
}
}
}
}
}

Not a simple answer, but I think you have two approaches available.
subclass the input components (UITextView, UITextField, etc) as you've done with the UIWindow.
Create a application wide UITextViewDelegate (and UITextFieldDelegate) and assign all your input field delegates to it.

Related

Unhiding a view is very slow in CTCallCenter callEventHandler

Reposting with more concise and focused question after original question went unanswered. Also adding more insight into the problem after another day of research:
In my app delegate (didFinishLaunching), I set up a callEventHandler on CTCallCenter.
The idea is that when a callState changes, I post a notification with a userInfo dict
containing the call.callState. In my view, I observe this notification, and when the
userInfo dict contains a value of CTCallDisconnected, I want to unhide a view.
The problem I'm having is that the unhiding aspect is taking, almost consistenly, ~ 7 seconds.
Everything else is working fine, and I know this because I NSLog before and after the unhiding,
and those logs appear immediately, but the darned view still lags for 7 seconds.
Here's my code:
appDidFinishLaunching:
self.callCenter = [[CTCallCenter alloc] init];
self.callCenter.callEventHandler = ^(CTCall* call) {
// anounce that we've had a state change in our call center
NSDictionary *dict = [NSDictionary dictionaryWithObject:call.callState forKey:#"callState"];
[[NSNotificationCenter defaultCenter] postNotificationName:#"CTCallStateDidChange" object:self userInfo:dict];
};
I then listen for this notification when a user taps a button that dials a phone number:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(ctCallStateDidChange:) name:#"CTCallStateDidChange" object:nil];
Then, in ctCallStateDidChange:
- (void)ctCallStateDidChange:(NSNotification *)notification
{
NSLog(#"121");
NSString *callInfo = [[notification userInfo] objectForKey:#"callState"];
if ([callInfo isEqualToString:CTCallStateDisconnected]) {
NSLog(#"before show");
[self.view viewWithTag:kNONEMERGENCYCALLSAVEDTOLOG_TAG].hidden = NO;
NSLog(#"after show");
}
}
I've tracked the problem down to the if condition in the above code sample:
if ([[userInfo valueForKey:#"userInfo"] valueForKey:#"callState"] == CTCallStateDisconnected) {
If I simply replace that with:
if (1 == 1) {
Then the view appears immediately!
The thing is, those NSLog statements are logging immediately, but the view is
lagging in it's unhiding. How could that condition cause only part of it's block
to execute immediately, and the rest to wait ~ 7 seconds?
Thanks!
Try changing your code to this:
- (void)ctCallStateDidChange:(NSNotification *)notification
{
NSLog(#"121");
NSString *callInfo = [[notification userInfo] objectForKey:#"callState"];
if ([callInfo isEqualToString:CTCallStateDisconnected]) {
NSLog(#"before show");
[self.view viewWithTag:kNONEMERGENCYCALLSAVEDTOLOG_TAG].hidden = NO;
NSLog(#"after show");
}
}
Note:
The parameter is an NSNotification, not an NSDictionary
I would not compare strings with ==
No need to cast the view to change the hidden property
Use NO instead of false
Update: Got an idea: Could you try the following, please, in between the NSLogs?
dispatch_async(dispatch_get_main_queue(), ^{
[self.view viewWithTag:kNONEMERGENCYCALLSAVEDTOLOG_TAG].hidden = NO;
});
Reading the CTCallCenter doc, it seems the callEventHandler is dispatched on "the default priority global dispatch queue", which is not the main queue where all the UI stuff happens.
Looks like there is no problem with your hidden code. If I were you, I would comment out all the code after the call ends, and uncomment them one by one to see what is the problem.
Hm... try to call [yourViewController.view setNeedsDisplay] after you change hidden property. Or avoid hidden, use alpha or addSubview: and removeFromSuperview methods instead.
djibouti33,
Where you put this sentence to listen when a user taps a button that dials a phone number?on WillResignActive function?
this sentence --> [[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(ctCallStateDidChange:) name:#"CTCallStateDidChange" object:nil];
Thanks for your time,
Willy.

Specific expression in if condition causes 7 second delay in execution [duplicate]

Reposting with more concise and focused question after original question went unanswered. Also adding more insight into the problem after another day of research:
In my app delegate (didFinishLaunching), I set up a callEventHandler on CTCallCenter.
The idea is that when a callState changes, I post a notification with a userInfo dict
containing the call.callState. In my view, I observe this notification, and when the
userInfo dict contains a value of CTCallDisconnected, I want to unhide a view.
The problem I'm having is that the unhiding aspect is taking, almost consistenly, ~ 7 seconds.
Everything else is working fine, and I know this because I NSLog before and after the unhiding,
and those logs appear immediately, but the darned view still lags for 7 seconds.
Here's my code:
appDidFinishLaunching:
self.callCenter = [[CTCallCenter alloc] init];
self.callCenter.callEventHandler = ^(CTCall* call) {
// anounce that we've had a state change in our call center
NSDictionary *dict = [NSDictionary dictionaryWithObject:call.callState forKey:#"callState"];
[[NSNotificationCenter defaultCenter] postNotificationName:#"CTCallStateDidChange" object:self userInfo:dict];
};
I then listen for this notification when a user taps a button that dials a phone number:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(ctCallStateDidChange:) name:#"CTCallStateDidChange" object:nil];
Then, in ctCallStateDidChange:
- (void)ctCallStateDidChange:(NSNotification *)notification
{
NSLog(#"121");
NSString *callInfo = [[notification userInfo] objectForKey:#"callState"];
if ([callInfo isEqualToString:CTCallStateDisconnected]) {
NSLog(#"before show");
[self.view viewWithTag:kNONEMERGENCYCALLSAVEDTOLOG_TAG].hidden = NO;
NSLog(#"after show");
}
}
I've tracked the problem down to the if condition in the above code sample:
if ([[userInfo valueForKey:#"userInfo"] valueForKey:#"callState"] == CTCallStateDisconnected) {
If I simply replace that with:
if (1 == 1) {
Then the view appears immediately!
The thing is, those NSLog statements are logging immediately, but the view is
lagging in it's unhiding. How could that condition cause only part of it's block
to execute immediately, and the rest to wait ~ 7 seconds?
Thanks!
Try changing your code to this:
- (void)ctCallStateDidChange:(NSNotification *)notification
{
NSLog(#"121");
NSString *callInfo = [[notification userInfo] objectForKey:#"callState"];
if ([callInfo isEqualToString:CTCallStateDisconnected]) {
NSLog(#"before show");
[self.view viewWithTag:kNONEMERGENCYCALLSAVEDTOLOG_TAG].hidden = NO;
NSLog(#"after show");
}
}
Note:
The parameter is an NSNotification, not an NSDictionary
I would not compare strings with ==
No need to cast the view to change the hidden property
Use NO instead of false
Update: Got an idea: Could you try the following, please, in between the NSLogs?
dispatch_async(dispatch_get_main_queue(), ^{
[self.view viewWithTag:kNONEMERGENCYCALLSAVEDTOLOG_TAG].hidden = NO;
});
Reading the CTCallCenter doc, it seems the callEventHandler is dispatched on "the default priority global dispatch queue", which is not the main queue where all the UI stuff happens.
Looks like there is no problem with your hidden code. If I were you, I would comment out all the code after the call ends, and uncomment them one by one to see what is the problem.
Hm... try to call [yourViewController.view setNeedsDisplay] after you change hidden property. Or avoid hidden, use alpha or addSubview: and removeFromSuperview methods instead.
djibouti33,
Where you put this sentence to listen when a user taps a button that dials a phone number?on WillResignActive function?
this sentence --> [[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(ctCallStateDidChange:) name:#"CTCallStateDidChange" object:nil];
Thanks for your time,
Willy.

Why is MPMovieDurationAvailableNotification only getting dispatched once for my many instances of my MPMoviePlayerController?

I've got a UITableView which lists movie files from on disk. For each cell row, there is a worker instance allocated for each visible row, used to generate a thumbnail for the movie file and get its duration to display in the row.
For each instance of MPMoviePlayerController in the worker class Im listening for a MPMovieDurationAvailableNotification event from the movie player. For some reason this event only seems to be dispatched (or at least Im only able to catch it) from one of the worker instances. Here is the init and listener code. There are a few comments inline.
- (id) initWithRequestAsset:(RequestAsset *)asset {
if (self = [super init]) {
self.requestAsset = asset;
self.moviePlayer = [MPMoviePlayerController alloc];
[self setupMoviePlayerListeners];
[self.moviePlayer initWithContentURL:self.requestAsset.urlPath];
self.moviePlayer.shouldAutoplay = NO;
// I've also tried to retain the moviePlayer, to no avail
[self.moviePlayer release];
}
return self;
}
- (void) setupMoviePlayerListeners {
//
// If the object: is set to nil then Im able to catch three notifications, but they are all from last instance of the MPMoviePlayerController
//
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(onMovieDurationAvailable:)
name:MPMovieDurationAvailableNotification
object:self.moviePlayer];
}
- (void) onMovieDurationAvailable:(NSNotification *)notification {
NSLog(#"duration received notification");
self.requestAsset.duration = [[notification object] duration];
[[NSNotificationCenter defaultCenter] removeObserver:self name:MPMovieDurationAvailableNotification object:self.moviePlayer];
}
What am I doing wrong? I figured if I were to set the object: parameter to the instance of the MPMoviePlayerController it would allow me to get only the event for that instance. However, it appears that Im only getting the last notification dispatched.
You can only have 1 active MPMoviePlayerController instance. You can create multiple but only 1 will work at a time.
See (about 2 screens down):
http://developer.apple.com/library/ios/#documentation/MediaPlayer/Reference/MPMoviePlayerController_Class/Reference/Reference.html
"Note: Although you can create multiple MPMoviePlayerController objects and present their views in your interface, only one movie player at a time can play its movie."

iphone keyboard touch events

I need to be able to detect touch events on the keyboard. I have an app which shows a screen which occurs after a certain period of inactivity (i.e. no touch events) To solve this issue, I have subclassed my UIWindow and implemented the sendEvent function, which allows me to get touch events on the whole application by implementing the method in one place. This works everywhere beside when the keyboard is presented and the user is typing on the keyboard. What I need to know is that is there a way to detect touch events on the keyboard, kind of like what sentEvent does for uiWindow. Thanks in advance.
found a solution to the problem. if you observe the following notifications, you are able to get an event when the key is pressed. I added these notifications in my custom uiwindow class so doing it at one place will allow me to get these touch events throughout the application.
[[NSNotificationCenter defaultCenter] addObserver: self selector: #selector(keyPressed:) name: UITextFieldTextDidChangeNotification object: nil];
[[NSNotificationCenter defaultCenter] addObserver: self selector: #selector(keyPressed:) name: UITextViewTextDidChangeNotification object: nil];
- (void)keyPressed:(NSNotification*)notification
{ [self resetIdleTimer]; }
anyways, hope it helps someone else.
iPhoneDev: here is what I am doing.
I have a custom UIWindow object. In this object, there is a NSTimer that is reset whenever there is a touch. To get this touch you have to override the sendEvent method of UIWindow.
this is what the sendEvent method looks like in my custom window class:
- (void)sendEvent:(UIEvent *)event
{
if([super respondsToSelector: #selector(sendEvent:)])
{
[super sendEvent:event];
}
else
{
NSLog(#"%#", #"CUSTOM_Window super does NOT respond to selector sendEvent:!");
ASSERT(false);
}
// 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)
{
// anyObject works here.
UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase;
if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded)
{
[self resetIdleTimer];
}
}
}
here is the resetIdleTimer:
- (void)resetIdleTimer
{
if (self.idleTimer)
{
[self.idleTimer invalidate];
}
self.idleTimer = [NSTimer scheduledTimerWithTimeInterval:PASSWORD_TIMEOUT_INTERVAL target:self selector:#selector(idleTimerExceeded) userInfo:nil repeats:NO];
}
after this, in the idleTimerExceeded, I send a message to the window delegates, (in this case, the appDelegate).
- (void)idleTimerExceeded
{
[MY_CUSTOM_WINDOW_Delegate idleTimeLimitExceeded];
}
When I create this custom window object in the appDelegate, I set the appDelegate as the delegate for this window. And in the appDelegate definition of idleTimeLimitExceeded is where I do what I have to when the timer expires. They key thing is the create the custom window and override the sendEvent function. Combine this with the two keyboard notification shown above I added in the init method of the custom window class and you should be able to get 99% of all touch events on screen anywhere in the application.

iPhone sdk pass messages between view controllers

I was wondering what is the best practice for an application flow in iPhone development.
How do you pass messages between ViewControllers?
Do you use singletons? pass it between views or do you have a main controller for the application that manage the flow?
Thanks.
I use NSNotificationCenter, which is fantastic for this kind of work. Think of it as an easy way to broadcast messages.
Each ViewController you want to receive the message informs the default NSNotificationCenter that it wants to listen for your message, and when you send it, the delegate in every attached listener is run. For example,
ViewController.m
NSNotificationCenter *note = [NSNotificationCenter defaultCenter];
[note addObserver:self selector:#selector(eventDidFire:) name:#"ILikeTurtlesEvent" object:nil];
/* ... */
- (void) eventDidFire:(NSNotification *)note {
id obj = [note object];
NSLog(#"First one got %#", obj);
}
ViewControllerB.m
NSNotificationCenter *note = [NSNotificationCenter defaultCenter];
[note addObserver:self selector:#selector(awesomeSauce:) name:#"ILikeTurtlesEvent" object:nil];
[note postNotificationName:#"ILikeTurtlesEvent" object:#"StackOverflow"];
/* ... */
- (void) awesomeSauce:(NSNotification *)note {
id obj = [note object];
NSLog(#"Second one got %#", obj);
}
Would produce (in either order depending on which ViewController registers first):
First one got StackOverflow
Second one got StackOverflow
The NSNotification class is a bit heavyweight, but fits the usage you describe. The way it works is that your various NSViewControllers register with an NSNotificationCenter to receive the events they're interested in
Cocoa Touch handles the routing, including providing a singleton-like "default notification center" for you. See Apple's notification guide with more info.