封闭 Catch 并非详尽无遗(录音)
Posted
技术标签:
【中文标题】封闭 Catch 并非详尽无遗(录音)【英文标题】:Enclosing Catch is not Exhaustive (Audio Recording) 【发布时间】:2016-08-03 14:47:15 【问题描述】:我正在设置录音机,但在 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()
【问题讨论】:
【参考方案1】:错误信息具有误导性。一个
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
【讨论】:
【参考方案2】:您可以做几件事。
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
这应该可行。
【讨论】:
以上是关于封闭 Catch 并非详尽无遗(录音)的主要内容,如果未能解决你的问题,请参考以下文章