Delete specified file from document directory

我想从我的应用程序文档目录中删除一个图像。我编写的删除图像代码是:

 -(void)removeImage:(NSString *)fileName
{
fileManager = [NSFileManager defaultManager];
paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsPath = [paths objectAtIndex:0];
filePath = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", fileName]];
[fileManager removeItemAtPath:filePath error:NULL];
UIAlertView *removeSuccessFulAlert=[[UIAlertView alloc]initWithTitle:@"Congratulation:" message:@"Successfully removed" delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
[removeSuccessFulAlert show];
}

部分起作用了。这段代码从目录中删除文件,但是当我检查目录中的内容时,它仍然显示图像名。我要从目录中完全删除该文件。我应该在代码中改变什么来做同样的事情?谢谢

114741 次浏览

不要将错误设置为 NULL,而是将其设置为

NSError *error;
[fileManager removeItemAtPath:filePath error:&error];
if (error){
NSLog(@"%@", error);
}

这会告诉你它是否真的在删除文件

我检查了你的代码。它为我工作。检查任何错误,你正在得到使用修改后的代码如下

- (void)removeImage:(NSString *)filename
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];


NSString *filePath = [documentsPath stringByAppendingPathComponent:filename];
NSError *error;
BOOL success = [fileManager removeItemAtPath:filePath error:&error];
if (success) {
UIAlertView *removedSuccessFullyAlert = [[UIAlertView alloc] initWithTitle:@"Congratulations:" message:@"Successfully removed" delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
[removedSuccessFullyAlert show];
}
else
{
NSLog(@"Could not delete file -:%@ ",[error localizedDescription]);
}
}
    NSError *error;
[[NSFileManager defaultManager] removeItemAtPath:new_file_path_str error:&error];
if (error){
NSLog(@"%@", error);
}

Swift 3.0:

func removeImage(itemName:String, fileExtension: String) {
let fileManager = FileManager.default
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
guard let dirPath = paths.first else {
return
}
let filePath = "\(dirPath)/\(itemName).\(fileExtension)"
do {
try fileManager.removeItem(atPath: filePath)
} catch let error as NSError {
print(error.debugDescription)
}}

感谢@Anil Varghese,我在 Swift 2.0中编写了非常类似的代码:

static func removeImage(itemName:String, fileExtension: String) {
let fileManager = NSFileManager.defaultManager()
let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
guard let dirPath = paths.first else {
return
}
let filePath = "\(dirPath)/\(itemName).\(fileExtension)"
do {
try fileManager.removeItemAtPath(filePath)
} catch let error as NSError {
print(error.debugDescription)
}
}

Swift 2.0:

func removeOldFileIfExist() {
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
if paths.count > 0 {
let dirPath = paths[0]
let fileName = "someFileName"
let filePath = NSString(format:"%@/%@.png", dirPath, fileName) as String
if NSFileManager.defaultManager().fileExistsAtPath(filePath) {
do {
try NSFileManager.defaultManager().removeItemAtPath(filePath)
print("old image has been removed")
} catch {
print("an error during a removing")
}
}
}
}

可以使用 NSFileManager.defaultManager ()来双重保护文件删除。IsDeletableFileAtPath (PathName)现在必须使用 do {} catch {} ,因为旧的错误方法不再有效。 IsDeletableFileAtPath ()不是“抛出”(即。 “ public func RemoveItemAtPath (path: String) throw”) so it does not need the do...catch

let killFile = NSFileManager.defaultManager()


if (killFile.isDeletableFileAtPath(PathName)){




do {
try killFile.removeItemAtPath(arrayDictionaryFilePath)
}
catch let error as NSError {
error.description
}
}

我想从文档目录中删除 sqlite 数据库,我通过下面的回答成功地删除了 sqlite 数据库

NSString *strFileName = @"sqlite";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];


NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:NULL];
NSEnumerator *enumerator = [contents objectEnumerator];
NSString *filename;
while ((filename = [enumerator nextObject])) {
NSLog(@"The file name is - %@",[filename pathExtension]);
if ([[filename pathExtension] isEqualToString:strFileName]) {
[fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];
NSLog(@"The sqlite is deleted successfully");
}
}

如果你对现代 api 方式感兴趣,避免使用 NSSearchPath 和文档目录中的过滤器文件,在删除之前,你可以这样做:

let fileManager = FileManager.default
let keys: [URLResourceKey] = [.nameKey, .isDirectoryKey]
let options: FileManager.DirectoryEnumerationOptions = [.skipsHiddenFiles, .skipsPackageDescendants]
guard let documentsUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask).last,
let fileEnumerator = fileManager.enumerator(at: documentsUrl,
includingPropertiesForKeys: keys,
options: options) else { return }


let urls: [URL] = fileEnumerator.flatMap { $0 as? URL }
.filter { $0.pathExtension == "exe" }
for url in urls {
do {
try fileManager.removeItem(at: url)
} catch {
assertionFailure("\(error)")
}
}

FreeGor version converted to Swift 3.0

 func removeOldFileIfExist() {
let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
if paths.count > 0 {
let dirPath = paths[0]
let fileName = "filename.jpg"
let filePath = NSString(format:"%@/%@", dirPath, fileName) as String
if FileManager.default.fileExists(atPath: filePath) {
do {
try FileManager.default.removeItem(atPath: filePath)
print("User photo has been removed")
} catch {
print("an error during a removing")
}
}
}
}

在斯威夫特3和4

 func removeImageLocalPath(localPathName:String) {
let filemanager = FileManager.default
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask,true)[0] as NSString
let destinationPath = documentsPath.appendingPathComponent(localPathName)
do {
try filemanager.removeItem(atPath: destinationPath)
print("Local path removed successfully")
} catch let error as NSError {
print("------Error",error.debugDescription)
}
}

或者 此方法可以删除所有本地文件

func deletingLocalCacheAttachments(){
let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
do {
let fileURLs = try fileManager.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
if fileURLs.count > 0{
for fileURL in fileURLs {
try fileManager.removeItem(at: fileURL)
}
}
} catch {
print("Error while enumerating files \(documentsURL.path): \(error.localizedDescription)")
}
}