从文档目录中的目录中删除文件?

41 nsfilemanager ios nsdocumentdirectory swift

我创建了一个Temp目录来存储一些文件:

//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)
   }
}
Run Code Online (Sandbox Code Playgroud)

没关系,现在我要删除目录中的所有文件......我试过如下:

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)")
    }
}
Run Code Online (Sandbox Code Playgroud)

我注意到文件仍在那里......我做错了什么?

joe*_*ern 54

如果有人需要这个最新的Swift/Xcode版本:这是一个从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)")
    }
}
Run Code Online (Sandbox Code Playgroud)

Swift 3.xSwift 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)")
    }
}
Run Code Online (Sandbox Code Playgroud)


rck*_*nes 20

两件事,使用temp目录,然后第二次传递错误fileManager.removeItemAtPath并将其放在if中以查看失败的内容.此外,您不应该检查是否设置了错误,而是检查方法是否返回数据.

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)")
    }
}
Run Code Online (Sandbox Code Playgroud)

要获得正确的临时目录使用 NSTemporaryDirectory()


Mak*_*zev 14

斯威夫特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)")
    }
}
Run Code Online (Sandbox Code Playgroud)


Hix*_*eld 13

Swift 4.0示例,它从diskcache文档目录中的示例文件夹" "中删除所有文件.我发现上面的例子不清楚,因为他们使用的NSTemporaryDirectory() + filePath不是"url"风格.为了您的方便:

    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)
        }
    }
Run Code Online (Sandbox Code Playgroud)


Hiề*_* Đỗ 6

从文档目录中删除所有文件: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
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这与过去 3 年发布的其他 6 个答案有何不同?添加一些解释以说明这是一个有用的答案。 (4认同)