Question

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?

Was it helpful?

Solution

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;
}

OTHER TIPS

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
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top