CaMenz
CaMenz

Reputation: 121

How to store Audio Data into Documents Directory?

I have an AVAudioPlayer, and I want to store its data into the documents directory as an audio file. But I can't seem to make it work. I've tried using FileManager, and AudioData.write(to: URL) and a bunch of other functions, but all of them are throwing errors saying the file doesn't exist or that it can't save on the documents folder.

Upvotes: 0

Views: 1856

Answers (1)

Razib Mollick
Razib Mollick

Reputation: 5052

[Swift 4] First create destination URL (document folder with file name) and then download the song to save. Please see the saving part code in side the below code.

func saveFile(url:URL){
let docUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
let desURL = docUrl.appendingPathComponent("tmpsong.m4a") //Use file name with ext
var downloadTask:URLSessionDownloadTask
downloadTask = URLSession.shared.downloadTask(with: url, completionHandler: { [weak self](URLData, response, error) -> Void in
    do{
        let isFileFound:Bool? = FileManager.default.fileExists(atPath: desURL.path)
        if isFileFound == true{
            print(desURL)
        } else {
            try FileManager.default.copyItem(at: URLData!, to: desURL)
        }

    }catch let err {
        print(err.localizedDescription)
    }
})
downloadTask.resume()
}

Upvotes: 3

Related Questions