Reputation: 69757
This is my working code in Swift. The issue is that I'm using UInt
as an intermediary type.
func handleInterruption(notification: NSNotification) {
let interruptionType = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as! UInt
if (interruptionType == AVAudioSessionInterruptionType.Began.rawValue) {
// started
} else if (interruptionType == AVAudioSessionInterruptionType.Ended.rawValue) {
// ended
let interruptionOption = notification.userInfo?[AVAudioSessionInterruptionOptionKey] as! UInt
if interruptionOption == AVAudioSessionInterruptionOptions.OptionShouldResume.rawValue {
// resume!
}
}
}
Is there a better way?
Upvotes: 0
Views: 1826
Reputation: 42449
This approach is similar to Matt's, but due to changes with Swift 3 (mainly userInfo
being [AnyHashable : Any]
), we can make our code a little more "Swifty" (no switching on rawValue
or casting to AnyObject
, etc.):
func handleInterruption(notification: Notification) {
guard let userInfo = notification.userInfo,
let interruptionTypeRawValue = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt,
let interruptionType = AVAudioSessionInterruptionType(rawValue: interruptionTypeRawValue) else {
return
}
switch interruptionType {
case .began:
print("interruption began")
case .ended:
print("interruption ended")
}
}
Upvotes: 5
Reputation: 642
NSNotificationCenter.defaultCenter().addObserver(self,selector: #selector(PlayAudioFile.audioInterrupted), name: AVAudioSessionInterruptionNotification, object: AVAudioSession.sharedInstance())
func audioInterrupted(noti: NSNotification) {
guard noti.name == AVAudioSessionInterruptionNotification && noti.userInfo != nil else {
return
}
if let typenumber = noti.userInfo?[AVAudioSessionInterruptionTypeKey]?.unsignedIntegerValue {
switch typenumber {
case AVAudioSessionInterruptionType.Began.rawValue:
print("interrupted: began")
case AVAudioSessionInterruptionType.Ended.rawValue:
print("interrupted: end")
default:
break
}
}
}
Upvotes: 3
Reputation: 534950
let interruptionType =
notification.userInfo?[AVAudioSessionInterruptionTypeKey] as! UInt
if (interruptionType == AVAudioSessionInterruptionType.Began.rawValue) {
The only thing I don't like about that code is the forced as!
. You're making some big assumptions here, and big assumptions can lead to crashes. Here's a safer way:
let why : AnyObject? = note.userInfo?[AVAudioSessionInterruptionTypeKey]
if let why = why as? UInt {
if let why = AVAudioSessionInterruptionType(rawValue: why) {
if why == .Began {
Otherwise, what you're doing is simply how you have to do it.
Upvotes: 4