3

In my app, the user can say a command into his microphone when he presses a UIButton on screen (and it stops listening when he presses it again) and it then executes some code (-> this works).

I would like to do the same when the user presses his play/pause button on his headphones instead of the UIButton on screen (and that he is on this VC).

I've seen quite a few tutorials about how to use the iPhone headphones' play/pause button but I haven't been able to make them work for me.

I do not manage to catch the button press, it just keeps playing/pausing music from my library.

Currently the VC where I have the UIButton, this is the code I added, but I never enter the remoteControlReceived function:

override var canBecomeFirstResponder : Bool {
    return true
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    self.becomeFirstResponder()
    UIApplication.shared.beginReceivingRemoteControlEvents()
}

override func remoteControlReceived(with event: UIEvent?) {
    if (event?.type == UIEventType.remoteControl) {
        if event?.subtype == UIEventSubtype.remoteControlTogglePlayPause {
            //execute the code ...
        }
    }
}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Charles Rostaing
  • 548
  • 5
  • 17
  • https://developer.apple.com/library/content/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/HandlingAudioHardwareRouteChanges/HandlingAudioHardwareRouteChanges.html – Sachin Vas Dec 06 '16 at 10:07
  • 1
    Thanks for the link. From what I see on the website, I cannot perform what I want to do ? What I understand is that the headphone buttons only allow to use media player features. Is that correct ? I was looking to perform an action unrelated to media player (like there is on the camera app: pressing audio buttons takes a picture). In my case, press audio button executes a function in my code. – Charles Rostaing Dec 08 '16 at 08:24
  • http://stackoverflow.com/questions/15424578/how-can-we-handle-headphone-play-pause-button-events-in-foreground-in-ios – Sachin Vas Dec 08 '16 at 08:29
  • 1
    This does indeed confirm that it can be done. It's the same code as mine above except in obj-C. But I put a breakpoint on the first line of my remoteControlReceived and this breakpoint is never reached when i press any of the headphone buttons. UIBackgroundModes is replaced in my case by : 'Required background modes' in the new versions of xcode lplist. I selected 'app communicates with accessory' and treid also 'plays audio...' – Charles Rostaing Dec 08 '16 at 08:36
  • 1
    Use `MPRemoteCommandCenter` – Sachin Vas Dec 08 '16 at 08:39

0 Answers0