0

I'm in trouble with file deletion in Swift Here is the problem, when I list the directory content I see all files When I select the one to delete with some condition, when I try to delete That throw me an error which says that files doesn't exist...

Here is the function

 static func deleteAllVideosDownloaded() {

let fileManager = NSFileManager.defaultManager()
let directoryURL = fileManager.URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask)[0]
let enumerator: NSDirectoryEnumerator = fileManager.enumeratorAtPath(directoryURL.path!)!

while let element = enumerator.nextObject() as? String {

  let url = NSURL(string: element)
  let pathExtention = url!.pathExtension

  print("All Elements : \(element)")
  print("URL : \(url)")

  if pathExtention == GlobalConstants.videoExtension {
    print("Element = \(element)")
    let path = directoryURL.URLByAppendingPathComponent(element)
    Log.i("File Path : \(path)")
    do {
      try fileManager.removeItemAtPath(path.absoluteString)
    } catch let error as NSError {
      Log.e("Error while deleting a file: \(error)")
    }
  }
}
FileUtils.listCachesDirectoryContent()

}

If anyone sees what is wrong it'll be awesome, cause I'm stuck with since 3 hours at least.

Alexandre Odet
  • 75
  • 1
  • 1
  • 8
  • The code look fine. Maybe you want to let us know more like what is in your `GlobalConstants.videoExtension`? Also is all the `print` that you did is giving the expected response? – Zac Kwan Jul 22 '16 at 14:05
  • 2
    `.absoluteString` is the wrong method, use `.path` instead. Compare http://stackoverflow.com/questions/34135305/nsfilemanager-defaultmanager-fileexistsatpath-returns-false-instead-of-true for a similar issue. – Martin R Jul 22 '16 at 14:06
  • Maybe also print the `path.absoluteString` which is given to `removeItemAtPath`. This way you know, what exactly your code tries to delete. – Tali Jul 22 '16 at 14:06
  • ... or better, use `removeItemAtURL()`. – Martin R Jul 22 '16 at 14:08
  • @ZacKwan in GlobalConstants.videoExtension there is a string with "mp4" in it :) I compile and I'll print an image in the question for seeing the log ;) Thank you all – Alexandre Odet Jul 22 '16 at 14:10
  • @MartinR just try what you say, and it worked perfectly ! Thank you so much ! – Alexandre Odet Jul 22 '16 at 14:14

0 Answers0