Dan Rosenstark Dan Rosenstark - 6 months ago 83
Swift Question

How to Use Constants in Swift: AVAudioSessionInterruptionNotification

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?

Answer
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.