I'm sorry about asking this question which is discussed here many times once again. But none of the answers haven't really helped me. All I need is to put some simple code in a viewDidLoad
to check whether the headphones are plugged in or are not. (If they aren't I want to pop up simple message, but that's not what I'm asking how to do.) Any help?
Asked
Active
Viewed 2,086 times
2

TomasJ
- 289
- 8
- 21
-
This is a great question! Thanks for asking, it's interesting to learn the answer. – hybridcattt Oct 19 '13 at 21:44
2 Answers
9
This should achieve what you want (iOS 6+ compatible)
- (BOOL)areHeadphonesPluggedIn {
NSArray *availableOutputs = [[AVAudioSession sharedInstance] currentRoute].outputs;
for (AVAudioSessionPortDescription *portDescription in availableOutputs) {
if ([portDescription.portType isEqualToString:AVAudioSessionPortHeadphones]) {
return YES;
}
}
return NO;
}

Gabriele Petronella
- 106,943
- 21
- 217
- 235
-
Worked great! thank you. Anyway is there any other solution for older iOS? – TomasJ Oct 19 '13 at 19:51
-
I haven't tried, but there are several threads about it. This is one example: http://stackoverflow.com/questions/10685313/detecting-if-headset-are-plugged-into-ios-device – Gabriele Petronella Oct 19 '13 at 19:52
-
thanks, this works in iOS9. There are a number of older strings discussing this topic but they seem out of date. – BenHedges Jul 28 '16 at 20:36
2
Here is the Swift 1.2 Version of the code written by Gabriele Petronella
//This method checks if headphones are plugged in.
func areHeadphonesPluggedIn()->Bool
{
var availableOutputs = AVAudioSession.sharedInstance().currentRoute.outputs
for portDescription in availableOutputs
{
if portDescription.portType == AVAudioSessionPortHeadphones
{
return true
}
}
return false
}

Nish
- 21
- 1