我已经创建了一个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)
}
}
很好,现在我要删除目录中的所有文件...我尝试如下操作:
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)")
}
}
我注意到文件仍然在那里...我在做什么错?
最佳答案
有两件事,请使用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)")
}
}
要获得正确的临时目录,请使用
NSTemporaryDirectory()
关于ios - 从文档目录内的目录中删除文件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32840190/