Ios AVAudioRecorder线程1:EXC\u BAD\u访问(代码=1,地址=0x0)

Ios AVAudioRecorder线程1:EXC\u BAD\u访问(代码=1,地址=0x0),ios,avfoundation,Ios,Avfoundation,我在Udacity学习iOS课程。我不知道为什么要运行下面的代码。它将在try!的行中显示线程1:EXC\u BAD\u ACCESS(代码=1,地址=0x0)的消息!audioRecorder=AVAudioRecorder(url:filePath!,设置:[:]) 您使用了错误的API URL(string:用于表示完整URL的字符串,包括方案(http://,ftp://,文件://) 以斜杠开头的文件路径的正确API是URL(fileURLWithPath) 其次,NSSearchPa

我在Udacity学习iOS课程。我不知道为什么要运行下面的代码。它将在
try!的行中显示线程1:EXC\u BAD\u ACCESS(代码=1,地址=0x0)的消息!audioRecorder=AVAudioRecorder(url:filePath!,设置:[:])


您使用了错误的API

URL(string:
用于表示完整URL的字符串,包括方案(
http://
ftp://
文件://

以斜杠开头的文件路径的正确API是
URL(fileURLWithPath

其次,
NSSearchPathForDirectoriesInDomains
和手动连接路径组件已经过时。使用与URL相关的API,顺便解决了错误

let documentsURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let fileURL = documentsURL.appendingPathComponent("recordedVoice.wav")
try!
无法崩溃,因为如果文档文件夹不存在,操作系统将始终创建该文件夹

对于真正能够抛出错误的API,添加错误处理

do {

    try session.setCategory(AVAudioSessionCategoryPlayAndRecord, with:AVAudioSessionCategoryOptions.defaultToSpeaker)

    try audioRecorder = AVAudioRecorder(url: filePath!, settings: [:])
    audioRecorder.delegate = self
    ...

} catch { print(error) }

您使用了错误的API

URL(string:
用于表示完整URL的字符串,包括方案(
http://
ftp://
文件://

以斜杠开头的文件路径的正确API是
URL(fileURLWithPath

其次,
NSSearchPathForDirectoriesInDomains
和手动连接路径组件已经过时。使用与URL相关的API,顺便解决了错误

let documentsURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let fileURL = documentsURL.appendingPathComponent("recordedVoice.wav")
try!
无法崩溃,因为如果文档文件夹不存在,操作系统将始终创建该文件夹

对于真正能够抛出错误的API,添加错误处理

do {

    try session.setCategory(AVAudioSessionCategoryPlayAndRecord, with:AVAudioSessionCategoryOptions.defaultToSpeaker)

    try audioRecorder = AVAudioRecorder(url: filePath!, settings: [:])
    audioRecorder.delegate = self
    ...

} catch { print(error) }