Swift 3.0Swift 5.0存在错误

ios - getDocumentsDirectory Swift5替代-LMLPHP

代码:

//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)


ios - getDocumentsDirectory Swift5替代-LMLPHP

我认为应该是这样的:

   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)")
}

关于ios - getDocumentsDirectory Swift5替代,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59825092/

10-09 10:21