Upvote:2

- (void)viewDidLoad {
    [super viewDidLoad];

    NSError *setCategoryErr;
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr];

    // Detects when the audio route changes (ex: headphones unplugged)
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioHardwareRouteChanged:) name:AVAudioSessionRouteChangeNotification object:nil];
    // Don't forget to remove notification in dealloc method!!
}

- (void)audioHardwareRouteChanged:(NSNotification *)notification {
    NSInteger routeChangeReason = [notification.userInfo[AVAudioSessionRouteChangeReasonKey] integerValue];
    if (routeChangeReason == AVAudioSessionRouteChangeReasonOldDeviceUnavailable) {
        // if we're here, The old device is unavailable == headphones have been unplugged, so stop manually!
        [self.player stop];
    }
}

More Answer related to the Same Query

Upvote:2

let audioSession = AVAudioSession.sharedInstance()
_ = try? audioSession.setCategory(AVAudioSessionCategoryPlayback, with: .duckOthers)
_ = try? audioSession.setActive(true)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(audioRouteChanged), name: .AVAudioSessionRouteChange, object: nil)


func audioRouteChanged(note: Notification) {
   if let userInfo = note.userInfo {
       if let reason = userInfo[AVAudioSessionRouteChangeReasonKey] as? Int  {
       if reason == AVAudioSessionRouteChangeReason.oldDeviceUnavailable.hashValue {
       // headphones plugged out
       player.stop()
      }
    }
  }
}

Credit Goes to: stackoverflow.com

Related question with same questions but different answers