Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change AVAudio interruption and route change handlers to use guards #3

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 27 additions & 21 deletions Chapter 2/AudioLooper/AudioLooper/PlayerController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -112,32 +112,38 @@ class PlayerController: NSObject, AVAudioPlayerDelegate {
}

func handleInterruption(_ notification: Notification) {
if let info = (notification as NSNotification).userInfo {
let type = info[AVAudioSessionInterruptionTypeKey] as! AVAudioSessionInterruptionType
if type == .began {
stop()
delegate?.playbackStopped()
} else {
let options = info[AVAudioSessionInterruptionOptionKey] as! AVAudioSessionInterruptionOptions
if options == .shouldResume {
play()
delegate?.playbackBegan()
}
guard let info = notification.userInfo,
let typeValue = info[AVAudioSessionInterruptionTypeKey] as? UInt,
let type = AVAudioSessionInterruptionType(rawValue: typeValue) else {
return
}
if type == .began {
stop()
delegate?.playbackStopped()
}
else if type == .ended {
guard let optionsValue = info[AVAudioSessionInterruptionOptionKey] as? UInt else {
return
}
let options = AVAudioSessionInterruptionOptions(rawValue: optionsValue)
if options.contains(.shouldResume) {
play()
delegate?.playbackBegan()
}
}
}

func handleRouteChange(_ notification: Notification) {
if let info = (notification as NSNotification).userInfo {

let reason = info[AVAudioSessionRouteChangeReasonKey] as! AVAudioSessionRouteChangeReason
if reason == .oldDeviceUnavailable {
let previousRoute = info[AVAudioSessionRouteChangePreviousRouteKey] as! AVAudioSessionRouteDescription
let previousOutput = previousRoute.outputs.first!
if previousOutput.portType == AVAudioSessionPortHeadphones {
stop()
delegate?.playbackStopped()
}
guard let info = notification.userInfo,
let reason = info[AVAudioSessionRouteChangeReasonKey] as? AVAudioSessionRouteChangeReason else {
return
}
if reason == .oldDeviceUnavailable {
let previousRoute = info[AVAudioSessionRouteChangePreviousRouteKey] as! AVAudioSessionRouteDescription
let previousOutput = previousRoute.outputs.first!
if previousOutput.portType == AVAudioSessionPortHeadphones {
stop()
delegate?.playbackStopped()
}
}
}
Expand Down