从 Document 目录中的目录中删除文件?
Delete files from directory inside Document directory?
我创建了一个临时目录来存储一些文件:
//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 中以查看失败的原因。此外,您不应该检查是否设置了错误,而是检查方法是否具有 return 数据。
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()
如果有人需要最新的 Swift / Xcode 版本:这里是一个从临时文件夹中删除所有文件的示例:
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 和 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)")
}
}
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)")
}
}
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)
}
}
使用文件
https://github.com/JohnSundell/Files
do {
for folder:Folder in (FileSystem().documentFolder?.subfolders)! {
try folder.delete()
}
} catch _ {
print("Error")
}
在文档目录中创建临时文件夹 (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!
}
从临时目录中删除文件:(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)")
}
}
从文档目录中删除所有文件: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
}
}
经过研究,我找到了这个完美的解决方案,
您可以删除所有文件和文件夹,这将跳过隐藏文件(例如,.DS_Store)
func clearCache(){
let fileManager = FileManager.default
do {
let documentDirectoryURL = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let fileURLs = try fileManager.contentsOfDirectory(at: documentDirectoryURL, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
for url in fileURLs {
try fileManager.removeItem(at: url)
}
} catch {
print(error)
}
}
从应用文档文件夹中删除文件的简单功能。
func removeItem(_ relativeFilePath: String) {
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let absoluteFilePath = documentsDirectory.appendingPathComponent(relativeFilePath)
try? FileManager.default.removeItem(at: absoluteFilePath)
}
用法:
removeItem("path/to/file.txt")
我创建了一个临时目录来存储一些文件:
//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 中以查看失败的原因。此外,您不应该检查是否设置了错误,而是检查方法是否具有 return 数据。
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()
如果有人需要最新的 Swift / Xcode 版本:这里是一个从临时文件夹中删除所有文件的示例:
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 和 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)")
}
}
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)")
}
}
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)
}
}
使用文件
https://github.com/JohnSundell/Files
do {
for folder:Folder in (FileSystem().documentFolder?.subfolders)! {
try folder.delete()
}
} catch _ {
print("Error")
}
在文档目录中创建临时文件夹 (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!
}
从临时目录中删除文件:(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)")
}
}
从文档目录中删除所有文件: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
}
}
经过研究,我找到了这个完美的解决方案,
您可以删除所有文件和文件夹,这将跳过隐藏文件(例如,.DS_Store)
func clearCache(){
let fileManager = FileManager.default
do {
let documentDirectoryURL = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let fileURLs = try fileManager.contentsOfDirectory(at: documentDirectoryURL, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
for url in fileURLs {
try fileManager.removeItem(at: url)
}
} catch {
print(error)
}
}
从应用文档文件夹中删除文件的简单功能。
func removeItem(_ relativeFilePath: String) {
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let absoluteFilePath = documentsDirectory.appendingPathComponent(relativeFilePath)
try? FileManager.default.removeItem(at: absoluteFilePath)
}
用法:
removeItem("path/to/file.txt")