iosswiftheadset

remoteControlReceived(with event: UIEvent?) Doesn't triggered


I have audio recording/playing app. But I want to pause playing, when user uses play/pause button on the regular wired iPhone headset. So i implemented handling of remote events:

// MARK: Overrides
internal extension AppDelegate {
    override func remoteControlReceived(with event: UIEvent?) {
        super.remoteControlReceived(with: event)
        /* some other logic */
    }
}

Then I started receiving remote events in application: didFinishLaunchingWithOptions::

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
    application.beginReceivingRemoteControlEvents()
    becomeFirstResponder()
    /* some other logic */
    return true
}

But anyway remoteControlReceived(with event: UIEvent?) is never triggered.

Also I tried MPRemoteCommandCenter:

MPRemoteCommandCenter.shared().togglePlayPauseCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
    return .success
}

Doesn't triggered.

Swift or objective-c answers accepted :)

What is wrong? Or should I add something in .plist?


Solution

  • Ok, I found the reason.... I'm using my app to mix it's sound with other apps, so I'm activating audio session with mixWithOthers option:

    AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: [.mixWithOthers])
    

    But, if I'm using mixWithOthers, app stops to receive remote events. That means, that if I want to receive toggle play/pause event from headset, I can't use this option:

    AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
    

    This is weird, but this is what we have. So in my case I can't use headset buttons :(