문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top