Delete files from directory inside Document directory?

user4790024 picture user4790024 · Sep 29, 2015 · Viewed 52.4k times · Source

I have created a Temp directory to store some files:

//MARK: -create save delete from directory
func createTempDirectoryToStoreFile(){
    var error: NSError?
    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    let documentsDirectory: AnyObject = paths[0]
    tempPath = documentsDirectory.stringByAppendingPathComponent("Temp")

    if (!NSFileManager.defaultManager().fileExistsAtPath(tempPath!)) {

        NSFileManager.defaultManager() .createDirectoryAtPath(tempPath!, withIntermediateDirectories: false, attributes: nil, error: &error)
   }
}

It's fine, now I want to delete all the files that are inside the directory... I tried as below:

func clearAllFilesFromTempDirectory(){

    var error: NSErrorPointer = nil
    let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
    var tempDirPath = dirPath.stringByAppendingPathComponent("Temp")
    var directoryContents: NSArray = fileManager.contentsOfDirectoryAtPath(tempDirPath, error: error)!

    if error == nil {
        for path in directoryContents {
            let fullPath = dirPath.stringByAppendingPathComponent(path as! String)
            let removeSuccess = fileManager.removeItemAtPath(fullPath, error: nil)
        }
    }else{

        println("seomthing went worng \(error)")
    }
}

I notice that files are still there... What am I doing wrong?

Answer

joern picture joern · Nov 26, 2015

In case anyone needs this for the latest Swift / Xcode versions: here is an example to remove all files from the temp folder:

Swift 2.x:

func clearTempFolder() {
    let fileManager = NSFileManager.defaultManager()
    let tempFolderPath = NSTemporaryDirectory()
    do {
        let filePaths = try fileManager.contentsOfDirectoryAtPath(tempFolderPath)
        for filePath in filePaths {
            try fileManager.removeItemAtPath(tempFolderPath + filePath)
        }
    } catch {
        print("Could not clear temp folder: \(error)")
    }
}

Swift 3.x and Swift 4:

func clearTempFolder() {
    let fileManager = FileManager.default
    let tempFolderPath = NSTemporaryDirectory()
    do {
        let filePaths = try fileManager.contentsOfDirectory(atPath: tempFolderPath)
        for filePath in filePaths {
            try fileManager.removeItem(atPath: tempFolderPath + filePath)
        }
    } catch {
        print("Could not clear temp folder: \(error)")
    }
}