How to Use Constants in Swift: AVAudioSessionInterruptionNotification

1.8k views Asked by At

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?

3

There are 3 answers

1
JAL On BEST ANSWER

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")
    }

}
0
matt On
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.

0
steve kim On
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
        }

    }
}