getDocumentsDirectory Swift5 替代方案

getDocumentsDirectory Swift5 alternative

Swift 3.0Swift 5.0

处出现错误

代码:

//Create audio file name URL
let audioFilename = getDocumentsDirectory().appendingPathComponent("audioRecording.m4a")

//Create the audio recording, and assign ourselves as the delegate
audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)

我看应该是这样的:

   func getDocumentsDirectory() -> URL
    {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let documentsDirectory = paths[0]
        return documentsDirectory
    }

是否正确?还是不行?

您可以使用以下代码:

func getDocumentsDirectory() throws -> URL {
     return try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
}

不要忘记处理异常情况,

try {
   let documents = try? getDocumentsDirectory()
   ...
} catch let error {
   print("something went wrong: \(error)")
}