Enclosing Catch不是穷举(录音)

时间:2016-08-03 14:47:16

标签: swift error-handling audio-recording avaudiorecorder

我正在设置录音机但在soundRecorder = try AVAudioRecorder(URL: getFileURL(), settings: recordSettings as! [String : AnyObject])上收到错误并出现以下错误Errors thrown from here are not handled because the enclosing catch is not exhaustive

func setUpRecorder() {

    let recordSettings = [AVFormatIDKey : Int(kAudioFormatAppleLossless), AVEncoderAudioQualityKey : AVAudioQuality.Max.rawValue, AVEncoderBitRateKey : 320000, AVNumberOfChannelsKey : 2, AVSampleRateKey : 44100.0 ]

    var error: NSError?

    do {
        //  soundRecorder = try AVAudioRecorder(URL: getFileURL(), settings: recordSettings as [NSObject : AnyObject])
        soundRecorder =  try AVAudioRecorder(URL: getFileURL(), settings: recordSettings as! [String : AnyObject])
    } catch let error1 as NSError {
        error = error1
        soundRecorder = nil
    }

    if let err = error {
        print("AVAudioRecorder error: \(err.localizedDescription)")
    } else {
        soundRecorder.delegate = self
        soundRecorder.prepareToRecord()
    }


}

2 个答案:

答案 0 :(得分:2)

错误消息具有误导性。一个

catch let error1 as NSError

是详尽无遗的,因为所有错误都被桥接到NSError 自动。

似乎编译器被强制转换混淆了

recordSettings as! [String : AnyObject]

,这会导致错误的错误消息。解决方案是创建 首先设置正确类型的设置字典:

let recordSettings: [String: AnyObject] = [
    AVFormatIDKey : Int(kAudioFormatAppleLossless),
    AVEncoderAudioQualityKey : AVAudioQuality.Max.rawValue,
    AVEncoderBitRateKey : 320000,
    AVNumberOfChannelsKey : 2,
    AVSampleRateKey : 44100.0 ]

var error: NSError?
do {
    soundRecorder = try AVAudioRecorder(URL: getFileURL(), settings: recordSettings)
} catch let error1 as NSError  {
    error = error1
    soundRecorder = nil
}

答案 1 :(得分:1)

你可以做几件事。

do {
    //  soundRecorder = try AVAudioRecorder(URL: getFileURL(), settings: recordSettings as [NSObject : AnyObject])
        soundRecorder =  try AVAudioRecorder(URL: getFileURL(), settings:     recordSettings as! [String : AnyObject])
    } catch let error1 as NSError {
        error = error1
        soundRecorder = nil
    } catch {
      //Exhaustive catch all.
    }
}

或者你可以像这样写

do {
    //  soundRecorder = try AVAudioRecorder(URL: getFileURL(), settings: recordSettings as [NSObject : AnyObject])
    soundRecorder =  try AVAudioRecorder(URL: getFileURL(), settings: recordSettings as! [String : AnyObject])
} catch {
  self.error = error as NSError
  soundRecorder = nil
}

这应该有效。