从文档目录中的目录中删除文件? [英] Delete files from directory inside Document directory?
问题描述
我创建了一个Temp目录来存储一些文件:
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?
推荐答案
两件事,使用 temp
目录,然后将错误传递给 fileManager.removeItemAtPath
并将其放在if中以查看失败的内容。此外,您不应该检查错误是否已设置,而是方法是否返回数据。
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)")
}
}
要获取正确的临时目录,请使用 NSTemporaryDirectory()
To get the correct temporary directory use NSTemporaryDirectory()
这篇关于从文档目录中的目录中删除文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!