iphone keyboard touch events - iphone

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.

Related

Detect user input using headsets

I'm trying to detect user input (a click) on the headphones connected to an iPhone. So far I've only found how to detect interruptions using AVAudioSession. Is AVAudioSession right or is there another way? how?
You want this:
beginReceivingRemoteControlEvents
You implement something this in one of your VCs classes:
// If using a nonmixable audio session category, as this app does, you must activate reception of
// remote-control events to allow reactivation of the audio session when running in the background.
// Also, to receive remote-control events, the app must be eligible to become the first responder.
- (void) viewDidAppear: (BOOL) animated {
[super viewDidAppear: animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
- (BOOL) canBecomeFirstResponder {
return YES;
}
// Respond to remote control events
- (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent {
if (receivedEvent.type == UIEventTypeRemoteControl) {
switch (receivedEvent.subtype) {
case UIEventSubtypeRemoteControlTogglePlayPause:
[self playOrStop: nil];
break;
default:
break;
}
}
}
See the sample code here.
It is even easier now, as of iOS 7. To execute a block when the headphone play/pause button is pressed:
MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
[commandCenter.togglePlayPauseCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
NSLog(#"toggle button pressed");
return MPRemoteCommandHandlerStatusSuccess;
}];
or, if you prefer to use a method instead of a block:
[commandCenter.togglePlayPauseCommand addTarget:self action:#selector(toggleButtonAction)];
To stop:
[commandCenter.togglePlayPauseCommand removeTarget:self];
or:
[commandCenter.togglePlayPauseCommand removeTarget:self action:#selector(toggleButtonAction)];
You'll need to add this to the includes area of your file:
#import MediaPlayer;

Can I detect if higher subview has been touched?

I've got a big UIView that responds to touches, and it's covered with lots of little UIViews that respond differently to touches. Is it possible to touch anywhere on screen and slide around, and have each view know if it's being touched?
For example, I put my finger down on the upper left and slide toward the lower right. The touchesBegan/Moved is collected by the baseView. As I pass over itemView1, itemView2, and itemView3, control passes to them. If I lift my finger while over itemView2, it performs itemView2's touchesEnded method. If I lift my finger over none of the items, it performs baseView's touchesEnded.
At the moment, if I touch down on baseView, touchEnded is always baseView and the higher itemViews are ignored.
Any ideas?
If I understand correctly, the touchesEnded event is detected, but not by the subview that needs to know about it. I think this might work for you:
In a common file, define TOUCHES_ENDED_IN_SUPERVIEW as #"touches ended in superview".
In the touchesEnded method of the containing view that is firing, add
[[NSNotificationCenter defaultCenter] postNotificationName: TOUCHES_ENDED_IN_SUPERVIEW object: self];
In the touchesBegan of the subviews, add
[[NSNotificationCenter defaultCenter] addObserver: self
selector: #selector(touchesEnded:)
name: TOUCHES_ENDED_IN_SUPERVIEW
object: self.superview];
In the touchesEnded methods of the subviews, use your normal logic for the event, and also add
[[NSNotificationCenter defaultCenter] removeObserver: self name: TOUCHES_ENDED_IN_SUPERVIEW object: self.superview];
Remember to put [[NSNotificationCenter defaultCenter] removeObserver: self] in your dealloc as well, in case it is possible to leave the page without getting the touchesEnded event.
You might want the notification to send its message to a special touchesEndedInSuperview method, which would invoke touchesEnded itself, but that depends on whether you have any special processing to do in that case.
You can use something like this:
-(void)touchesEnded: (NSSet *)touches
withEvent: (UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView: touch.view];
if (CGRectContainsPoint(control1.frame, location)) {
[self control1Action];
} else if (CGRectContainsPoint(control2.frame, location)) {
[self control2Action];
}
}

Receive iPhone keyboard events

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.

How does overlayViewTouched notification work in the MoviePlayer sample code

I have a question regarding the MoviePlayer sample code provided by apple.
I don't understand how the overlayViewTouch notification works. The NSlog message I added to it does not get sent when I touch the view (not button).
// post the "overlayViewTouch" notification and will send
// the overlayViewTouches: message
- (void)overlayViewTouches:(NSNotification *)notification
{
NSLog(#"overlay view touched");
// Handle touches to the overlay view (MyOverlayView) here...
}
I can, however, get the NSlog notification if I place it in -(void)touchesBegan in "MyOverlayView.m". Which makes me think it is recognizing touches but not sending a notification.
// Handle any touches to the overlay view
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch* touch = [touches anyObject];
if (touch.phase == UITouchPhaseBegan)
{
NSLog(#"overlay touched(from touchesBegan")
// IMPORTANT:
// Touches to the overlay view are being handled using
// two different techniques as described here:
//
// 1. Touches to the overlay view (not in the button)
//
// On touches to the view we will post a notification
// "overlayViewTouch". MyMovieViewController is registered
// as an observer for this notification, and the
// overlayViewTouches: method in MyMovieViewController
// will be called.
//
// 2. Touches to the button
//
// Touches to the button in this same view will
// trigger the MyMovieViewController overlayViewButtonPress:
// action method instead.
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:OverlayViewTouchNotification object:nil];
}
}
Can anyone shed light on what I am missing or doing wrong?
Thank you.
As it seems to me the sample code is missing the addObserver selector call to the Notification. An example of the registration can be found in the AppDelegate:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePreloadDidFinish:)
name:MPMoviePlayerContentPreloadDidFinishNotification
object:nil];
As in NSNotificationCenter Documentation
When an object (known as the notification sender) posts a notification, it sends an NSNotification object to the notification center. The notification center then notifies any observers for which the notification meets the criteria specified on registration by sending them the specified notification message, passing the notification as the sole argument.
If there are no observers no one will be informed by NSNotificationCenter.
Just add the appropriate register in init for example.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(overlayViewTouches:)
name:OverlayViewTouchNotification
object:nil];
It's because the overlay view is small. You can see the area covered by the overlay view by changing the background color of the overlay view. The notification will be delivered when you touch the area.

How to disable multitouch?

My app has several buttons which trigger different events. The user should NOT be able to hold down several buttons. Anyhow, holding down several buttons crashes the app.
And so, I'm trying to disable multi-touch in my app.
I've unchecked 'Multiple Touch' in all the xib files, and as far as I can work out, the properties 'multipleTouchEnabled' and 'exclusiveTouch' control whether the view uses multitouch. So in my applicationDidFinishLaunching I've put this:
self.mainViewController.view.multipleTouchEnabled = NO;
self.mainViewController.view.exclusiveTouch = YES;
And in each of my view controllers I've put this in the viewDidLoad
self.view.multipleTouchEnabled = NO;
self.view.exclusiveTouch = YES;
However, it still accepts multiple touches. I could do something like disable other buttons after getting a touch down event, but this would be an ugly hack. Surely there is a way to properly disable multi-touch?
If you want only one button to respond to touches at a time, you need to set exclusiveTouch for that button, rather than for the parent view. Alternatively, you could disable the other buttons when a button gets the "Touch Down" event.
Here's an example of the latter, which worked better in my testing. Setting exclusiveTouch for the buttons kind-of worked, but led to some interesting problems when you moved your finger off the edge of a button, rather than just clicking it.
You need to have outlets in your controller hooked up to each button, and have the "Touch Down", "Touch Up Inside", and "Touch Up Outside" events hooked to the proper methods in your controller.
#import "multibuttonsViewController.h"
#implementation multibuttonsViewController
// hook this up to "Touch Down" for each button
- (IBAction) pressed: (id) sender
{
if (sender == one)
{
two.enabled = false;
three.enabled = false;
[label setText: #"One"]; // or whatever you want to do
}
else if (sender == two)
{
one.enabled = false;
three.enabled = false;
[label setText: #"Two"]; // or whatever you want to do
}
else
{
one.enabled = false;
two.enabled = false;
[label setText: #"Three"]; // or whatever you want to do
}
}
// hook this up to "Touch Up Inside" and "Touch Up Outside"
- (IBAction) released: (id) sender
{
one.enabled = true;
two.enabled = true;
three.enabled = true;
}
#end
- (void)viewDidLoad {
[super viewDidLoad];
for(UIView* v in self.view.subviews)
{
if([v isKindOfClass:[UIButton class]])
{
UIButton* btn = (UIButton*)v;
[btn setExclusiveTouch:YES];
}
}
}
- (void)viewDidLoad {
[super viewDidLoad];
for(UIView* v in self.view.subviews)
{
if([v isKindOfClass:[UIButton class]])
{
UIButton* btn = (UIButton*)v;
[btn setExclusiveTouch:YES];
}
}
}
This code is tested and working perfectly for me.there is no app crash when pressing more than one button at a time.
Your app crashes for a reason. Investigate further, use the debugger, see what's wrong instead of trying to hide the bug.
Edit:
OK, ok, I have to admit I was a bit harsh. You have to set the exclusiveTouch property on each button. That's all. The multipleTouchEnabled property is irrelevant.
To disable multitouch in SWIFT:
You need first to have an outlet of every button and afterwards just set the exclusive touch to true.Therefore in you viewDidLoad() would have:
yourButton.exclusiveTouch = true.
// not really necessary but you could also add:
self.view.multipleTouchEnabled = false
If you want to disable multi touch throughout the application and don't want to write code for each button then you can simply use Appearance of button. Write below line in didFinishLaunchingWithOptions.
UIButton.appearance().isExclusiveTouch = true
Thats great!! UIAppearance
You can even use it for any of UIView class so if you want to disable multi touch for few buttons. Make a CustomClass of button and then
CustomButton.appearance().isExclusiveTouch = true
There is one more advantage which can help you. In case you want to disable multi touch of buttons in a particular ViewController
UIButton.appearance(whenContainedInInstancesOf: [ViewController2.self]).isExclusiveTouch = true
Based on neoevoke's answer, only improving it a bit so that it also checks subviews' children, I created this function and added it to my utils file:
// Set exclusive touch to all children
+ (void)setExclusiveTouchToChildrenOf:(NSArray *)subviews
{
for (UIView *v in subviews) {
[self setExclusiveTouchToChildrenOf:v.subviews];
if ([v isKindOfClass:[UIButton class]]) {
UIButton *btn = (UIButton *)v;
[btn setExclusiveTouch:YES];
}
}
}
Then, a simple call to:
[Utils setExclusiveTouchToChildrenOf:self.view.subviews];
... will do the trick.
This is quite often issue being reported by our testers. One of the approach that I'm using sometimes, although it should be used consciously, is to create category for UIView, like this one:
#implementation UIView (ExclusiveTouch)
- (BOOL)isExclusiveTouch
{
return YES;
}
Pretty much simple you can use make use of ExclusiveTouch property in this case
[youBtn setExclusiveTouch:YES];
This is a Boolean value that indicates whether the receiver handles touch events exclusively.
Setting this property to YES causes the receiver to block the delivery of touch events to other views in the same window. The default value of this property is NO.
For disabling global multitouch in Xamarin.iOS
Copy&Paste the code below:
[DllImport(ObjCRuntime.Constants.ObjectiveCLibrary, EntryPoint = "objc_msgSend")]
internal extern static IntPtr IntPtr_objc_msgSend(IntPtr receiver, IntPtr selector, bool isExclusiveTouch);
static void SetExclusiveTouch(bool isExclusiveTouch)
{
var selector = new ObjCRuntime.Selector("setExclusiveTouch:");
IntPtr_objc_msgSend(UIView.Appearance.Handle, selector.Handle, isExclusiveTouch);
}
And set it on AppDelegate:
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
...
SetExclusiveTouch(true); // setting exlusive to true disables the multitouch
...
}
My experience is that, by default, a new project doesn't even allow multitouch, you have to turn it on. But I suppose that depends on how you got started. Did you use a mutlitouch example as a template?
First of all, are you absolutely sure multitouch is on? It's possible to generate single touches in sequence pretty quickly. Multitouch is more about what you do with two or more fingers once they are on the surface. Perhaps you have single touch on but aren't correctly dealing with what happens if two buttons are pressed at nearly the same time.
I've just had exactly this problem.
The solution we came up with was simply to inherit a new class from UIButton that overrides the initWithCoder method, and use that where we needed one button push at a time (ie. everywhere):
#implementation ExclusiveButton
(id)initWithCoder: (NSCoder*)decoder
{
[self setExclusiveTouch:YES];
return [super initWithCoder:decoder]
}
#end
Note that this only works with buttons loaded from nib files.
I created UIView Class Extension and added this two functions. and when i want to disable view touch i just call [view makeExclusiveTouch];
- (void) makeExclusiveTouchForViews:(NSArray*)views {
for (UIView * view in views) {
[view makeExclusiveTouch];
}
}
- (void) makeExclusiveTouch {
self.multipleTouchEnabled = NO;
self.exclusiveTouch = YES;
[self makeExclusiveTouchForViews:self.subviews];
}
If you want to disable multitouch programmatically, or if you are using cocos2d (no multipleTouchEnabled option), you can use the following code on your ccTouches delegate:
- (BOOL)ccTouchesBegan:(NSSet *)touches
withEvent:(UIEvent *)event {
NSSet *multiTouch = [event allTouches];
if( [multiTouch count] > 1) {
return;
}
else {
//else your rest of the code
}
Disable all the buttons on view in "Touch Down" event and enable them in "Touch Up Inside" event.
for example
- (void) handleTouchDown {
for (UIButton *btn in views) {
btn.enable = NO;
}
}
- (void) handleTouchUpInside {
for (UIButton *btn in views) {
btn.enable = Yes;
}
------
------
}
I decided this problem by this way:
NSTimeInterval intervalButtonPressed;
- (IBAction)buttonPicturePressed:(id)sender{
if (([[NSDate date] timeIntervalSince1970] - intervalButtonPressed) > 0.1f) {
intervalButtonPressed = [[NSDate date] timeIntervalSince1970];
//your code for button
}
}
I had struggled with some odd cases when dragging objects around a view, where if you touched another object at the same time it would fire the touchesBegan method. My work-around was to disable user interaction for the parent view until touchesEnded or touchesCancelled is called.
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
// whatever setup you need
self.view.userInteractionEnabled = false
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
// whatever setup you need
self.view.userInteractionEnabled = true
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
// whatever setup you need
self.view.userInteractionEnabled = true
}
A Gotcha:
If you are using isExclusiveTouch, be aware that overriding point(inside:) on the button can interfere, effectively making isExclusiveTouch useless.
(Sometimes you need to override point(inside:) for handling the "button not responsive at bottom of iPhone screen" bug/misfeature (which is caused by Apple installing swipe GestureRecognizers at the bottom of the screen, interfering with button highlighting.)
See: UIButton fails to properly register touch in bottom region of iPhone screen
Just set all relevant UIView's property exclusiveTouch to false do the trick.