iphoneobjective-cheadphones

check whether headphones are plugged in when app starts


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?


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