Delete files from directory inside Document directory?

前端 未结 8 806
不思量自难忘°
不思量自难忘° 2020-12-24 01:48

I have created a Temp directory to store some files:

//MARK: -create save delete from directory
func createTempDirectoryToStoreFile(){
    var error: NSError         


        
8条回答
  •  無奈伤痛
    2020-12-24 02:24

    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)")
        }
    }
    

提交回复
热议问题