如何在 Swift 中使用常量:AVAudioSessionInterruptionNotification

How to Use Constants in Swift: AVAudioSessionInterruptionNotification

这是我在 Swift 中的工作代码。问题是我使用 UInt 作为中间类型。

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!                
        }
    }
}

有没有更好的方法?

let interruptionType =
    notification.userInfo?[AVAudioSessionInterruptionTypeKey] as! UInt
if (interruptionType == AVAudioSessionInterruptionType.Began.rawValue) {

我唯一不喜欢该代码的是强制 as!。你在这里做了一些大的假设,而大的假设可能会导致崩溃。这是一个更安全的方法:

let why : AnyObject? = note.userInfo?[AVAudioSessionInterruptionTypeKey]
if let why = why as? UInt {
    if let why = AVAudioSessionInterruptionType(rawValue: why) {
        if why == .Began {

否则,你所做的只是你必须做的事情。

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
        }

    }
}

这种方法类似于 Matt 的方法,但由于 Swift 3 的变化(主要是 userInfo 变为 [AnyHashable : Any]),我们可以使我们的代码多一点 "Swifty"(不打开 rawValue 或转换为 AnyObject,等等):

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

}