58

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?

Eric Aya
  • 69,473
  • 35
  • 181
  • 253

9 Answers9

71

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)")
    }
}
joern
  • 27,354
  • 7
  • 90
  • 105
32

Two things, use the temp directory and second pass an error to the fileManager.removeItemAtPath and place it in a if to see what failed. Also you should not be checking if the error is set but rather whether a methods has return data.

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 directoryContents != nil {
        for path in directoryContents {
            let fullPath = dirPath.stringByAppendingPathComponent(path as! String)
            if fileManager.removeItemAtPath(fullPath, error: error) == false {
                println("Could not delete file: \(error)")
            }
        }
    } else {
        println("Could not retrieve directory: \(error)")
    }
}

To get the correct temporary directory use NSTemporaryDirectory()

rckoenes
  • 69,092
  • 8
  • 134
  • 166
18

Swift 4.0 example that removes all files from an example folder "diskcache" in the documents directory. I found the above examples unclear because they used the NSTemporaryDirectory() + filePath which is not "url" style. For your convenience:

    func clearDiskCache() {
        let fileManager = FileManager.default
        let myDocuments = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
        let diskCacheStorageBaseUrl = myDocuments.appendingPathComponent("diskCache")
        guard let filePaths = try? fileManager.contentsOfDirectory(at: diskCacheStorageBaseUrl, includingPropertiesForKeys: nil, options: []) else { return }
        for filePath in filePaths {
            try? fileManager.removeItem(at: filePath)
        }
    }
HixField
  • 3,538
  • 1
  • 28
  • 54
16

Swift 3:

 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: NSTemporaryDirectory() + filePath)
        }
    } catch let error as NSError {
        print("Could not clear temp folder: \(error.debugDescription)")
    }
}
Ilia Khalyapin
  • 148
  • 1
  • 7
Yaroslav Dukal
  • 3,894
  • 29
  • 36
14

Remove all files From Document Directory: Swift 4

func clearAllFile() {
    let fileManager = FileManager.default
    let myDocuments = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
    do {
        try fileManager.removeItem(at: myDocuments)
    } catch {
        return
    }
}
Hiền Đỗ
  • 526
  • 6
  • 14
2

Create Temp Folder in Document Directory (Swift 4)

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

        let fileManager = FileManager.default
        if let tDocumentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first {
            let filePath =  tDocumentDirectory.appendingPathComponent("MY_TEMP")
            if !fileManager.fileExists(atPath: filePath.path) {
                do {
                    try fileManager.createDirectory(atPath: filePath.path, withIntermediateDirectories: true, attributes: nil)
                } catch {
                    NSLog("Couldn't create folder in document directory")
                    NSLog("==> Document directory is: \(filePath)")
                    return fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
                }
            }

            NSLog("==> Document directory is: \(filePath)")
            return filePath
        }
        return fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
    }

Remove Files From Temp Directory: (Swift 4)

func clearAllFilesFromTempDirectory(){        
        let fileManager = FileManager.default
        do {
            let strTempPath = getDocumentsDirectory().path
            let filePaths = try fileManager.contentsOfDirectory(atPath: strTempPath)
            for filePath in filePaths {
                try fileManager.removeItem(atPath: strTempPath + "/" + filePath)
            }
        } catch {
            print("Could not clear temp folder: \(error)")
        }
    }
Sandip Patel - SM
  • 3,346
  • 29
  • 27
2

After research, I find this perfect solution,

You can delete all files & folders, this will skip hidden files (for example, .DS_Store)

func clearCache(){
    let fileManager = FileManager.default
    do {
        let documentDirectoryURL = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
        let fileURLs = try fileManager.contentsOfDirectory(at: documentDirectoryURL, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
        for url in fileURLs {
           try fileManager.removeItem(at: url)
        }
    } catch {
        print(error)
    }
}
Mehul
  • 3,033
  • 23
  • 37
1

Using Files

https://github.com/JohnSundell/Files

    do {
        for folder:Folder in (FileSystem().documentFolder?.subfolders)! {
            try folder.delete()
        }
    } catch _ {
        print("Error")
    }
dimohamdy
  • 2,917
  • 30
  • 28
1

Simple func to delete a file from app Documents folder.

func removeItem(_ relativeFilePath: String) {
    guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
    let absoluteFilePath = documentsDirectory.appendingPathComponent(relativeFilePath)
    try? FileManager.default.removeItem(at: absoluteFilePath)
}

Usage:

removeItem("path/to/file.txt")
duyhungws
  • 321
  • 4
  • 9