How to switch between speaker and headphones output

I'm trying to mimic behaviour as in Phone app during calling. You can easily switch output sources from/to speaker or headphones.

I know I can force speaker as an output when headphones are connected by calling:

try! audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
try! audioSession.overrideOutputAudioPort(.speaker)


However, when I do that, I don't see any way to detect if headphones are still connected to the device.


I initially thought `outputDataSources` on AVAudioSession would return all posible outputs but it always returns nil.


Is there something I'm missing?