如何在Swift中使用常量:AVAudioSessionInterruptionNotification

Dan*_*ark 0 avaudioplayer ios swift

这是我在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!                
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?

JAL*_*JAL 5

这种方法类似于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")
    }

}
Run Code Online (Sandbox Code Playgroud)