如何在Swift中使用常量:AVAudioSessionInterruptionNotification

时间:2015-06-20 03:39:35

标签: ios swift avaudioplayer

这是我在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!                
        }
    }
}

有更好的方法吗?

3 个答案:

答案 0 :(得分:5)

这种方法与Matt类似,但由于Swift 3(主要是userInfo[AnyHashable : Any])的变化,我们可以使我们的代码多一点" Swifty&# 34; (无法启用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")
    }

}

答案 1 :(得分:4)

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 {

否则,您正在做的就是如何做到这一点。

答案 2 :(得分:3)

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
        }

    }
}