How do I handle interruptions like phone calls and Siri in Swift?

In Swift, handling interruptions such as phone calls or Siri can significantly improve the user experience of your app. To properly manage these interruptions, you need to make use of the AVAudioSession and appropriately respond to interruptions. Below is an example of how to set up your audio session to handle interruptions.

import AVFoundation class AudioSessionHandler { var audioSession: AVAudioSession! init() { audioSession = AVAudioSession.sharedInstance() do { try audioSession.setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker, .interruptSpokenAudioAndMixWithOthers]) try audioSession.setActive(true) NotificationCenter.default.addObserver(self, selector: #selector(handleInterruption), name: AVAudioSession.interruptionNotification, object: audioSession) } catch { print("Failed to set up audio session: \(error)") } } @objc func handleInterruption(notification: Notification) { guard let userInfo = notification.userInfo, let typeValue = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt, let type = AVAudioSession.InterruptionType(rawValue: typeValue) else { return } switch type { case .began: // Pause audio playback print("Audio interrupted, pausing playback.") case .ended: if let optionsValue = userInfo[AVAudioSessionInterruptionOptionKey] as? UInt { let options = AVAudioSession.InterruptionOptions(rawValue: optionsValue) if options.contains(.shouldResume) { // Resume audio playback print("Audio interruption ended, resuming playback.") } } default: break } } }

Swift AVAudioSession Interruptions Phone Calls Siri User Experience