Usunąć Pliki z katalogu wewnątrz katalogu dokumentu?

Utworzyłem katalog tymczasowy do przechowywania niektórych plików:

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

Jest dobrze, teraz chcę usunąć wszystkie pliki znajdujące się w katalogu... Próbowałem jak poniżej:

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

Zauważyłem, że pliki wciąż tam są... Co robię źle?

Author: Moritz, 2015-09-29

6 answers

Dwie rzeczy, użyj katalogu temp, a następnie przekaż błąd do fileManager.removeItemAtPath i umieść go w if, aby zobaczyć, co się nie udało. Nie powinieneś również sprawdzać, czy błąd jest ustawiony, ale raczej czy metoda ma dane zwrotne.

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

Aby uzyskać poprawny katalog tymczasowy użyj NSTemporaryDirectory()

 15
Author: rckoenes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-29 09:26:55

W przypadku, gdy ktoś potrzebuje tego dla najnowszych wersji Swift / Xcode: oto przykład, aby usunąć wszystkie pliki z folderu temp:

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 i 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)")
    }
}
 41
Author: joern,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-09 15:39:15

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)")
    }
}
 12
Author: Maksim Kniazev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-21 22:02:49

Przykład Swift 4.0 , który usuwa wszystkie pliki z przykładowego folderu "diskcache " w katalogu documents. Znalazłem powyższe przykłady niejasne, ponieważ używali NSTemporaryDirectory() + filePath, który nie jest stylem "url". Dla Twojej wygody:

    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)
        }
    }
 10
Author: HixField,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-04 19:54:20

Using Files

Https://github.com/JohnSundell/Files

    do {
        for folder:Folder in (FileSystem().documentFolder?.subfolders)! {
            try folder.delete()
        }
    } catch _ {
        print("Error")
    }
 1
Author: dimo hamdy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-09 13:39:35

Utwórz folder tymczasowy w katalogu dokumentu (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!
    }

Usuń Pliki Z Katalogu Tymczasowego: (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)")
        }
    }
 1
Author: Sandip Patel - SM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-27 11:27:41