cnichs27 cnichs27 - 4 months ago 19
Swift Question

Enclosing Catch is not Exhaustive (Audio Recording)

I am setting up an audio recorder but getting an error on

soundRecorder = try AVAudioRecorder(URL: getFileURL(), settings: recordSettings as! [String : AnyObject])
with the following error
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()
}


}

Answer

The error message is misleading. A

catch let error1 as NSError

is exhausting, because all errors are bridged to NSError automatically.

It seems that the compiler is confused by the forced cast

recordSettings as! [String : AnyObject]

and that causes the wrong error message. The solution is to create the settings dictionary with the correct type in the first place:

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
}