isicom
isicom

Reputation: 103

how to detect when middle headphone button is clicked

I want a single view application, where I detect a middle button click of my original iPhone headphone.

I tried with

- (void)remoteControlReceivedWithEvent:(UIEvent *)theEvent
{
    if (theEvent.type == UIEventTypeRemoteControl) {
        switch(theEvent.subtype) {
            case UIEventSubtypeRemoteControlTogglePlayPause:
                //Insert code

            case UIEventSubtypeRemoteControlPlay:
                //Insert code
                break;
            case UIEventSubtypeRemoteControlPause:
                // Insert code
                break;
            case UIEventSubtypeRemoteControlStop:
                //Insert code.
                break;
            default:
                return;
        }
    }
}

and

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];

    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
 }

and

- (BOOL) canBecomeFirstResponder {
    return YES;
}

But no chance :( There are no catchable events.

Does anyone have an idea?

Upvotes: 3

Views: 1484

Answers (1)

Fitsyu
Fitsyu

Reputation: 900

Tried all above but sadly now none seems to work. Then I took a peek at beginReceivingRemoteControlEvents and found this

In iOS 7.1 and later, use the shared MPRemoteCommandCenter object to register for remote control events. You do not need to call this method when using the shared command center object.

Then checked out MPRemoteCommandCenter and finally ended up in MPRemoteCommand documentation page.

Good thing is there is this example:

let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.playCommand.addTarget(handler: { (event) in    

    // Begin playing the current track    
    self.myMusicPlayer.play()
    return MPRemoteCommandHandlerStatus.success
})

Now if we want to read middle button we can do:

MPRemoteCommandCenter.shared().togglePlayPauseCommand.addTarget { (event: MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus in

 // middle button (toggle/pause) is clicked
 print("event:", event.command)

 return .success
}

This works and I managed to get the headphone's middle button detected.

Note: I noticed there is different behaviour that depends on where we put such code above. That is when I put in View Controller the reported events are identical and when I put it in AppDelegate's didFinishLaunching the reported events are different. Either way the event is detected.

Upvotes: 3

Related Questions