Search code examples
iosswift3swift5

getDocumentsDirectory Swift5 alternative


There is an error from Swift 3.0 at Swift 5.0

enter image description here

The code:

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

enter image description here

As I see it should be something like this:

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

Is it correct? Or not?


Solution

  • you can use following code:

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

    do not forget to handle exception case,

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