Kyle Gustov
Kyle Gustov

Reputation: 89

Trying to delete files from documents directory

I have an app that allows users to record multiple videos and then post them to view later from a database. After they post the video, I want the app to delete the video from the documents directory to save phone storage. I am trying this, but when i check my phone's storage nothing is updated. Here is what I am doing

This is where i write the video to:

func videoFileLocation() -> String {
    let uniqueID = NSUUID().uuidString
    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
    let outputPath = "\(documentsPath)/\(uniqueID).mov"
    return outputPath
}

This is how I remove them:

func clearDirectory() {
    do {
        data = try context.fetch(VideoPath.fetchRequest())

        for each in data {
            let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            let path = "\(documentsPath)/\(each.fileLocations!)"
            let url = URL(fileURLWithPath: path)
            do {
            try FileManager.default.removeItem(at: url)
                print("Successfully Cleared")
            } catch {
                print("There was a problem removing the file")
            }
}

The successfully cleared method gets printed out, but I see no change in my phone's storage. What am i doing wrong?

Upvotes: 0

Views: 221

Answers (1)

Joe
Joe

Reputation: 4074

Replace

let path = "\(documentsPath)/\(each.fileLocations!)"

with below and try.

var path: String = nil

if let fileLocationPath = each.fileLocations as? String {
  path = documentsPath.appendingPathComponent(fileLocationPath)
}

Upvotes: 1

Related Questions