ios 从文档目录中删除指定文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15017902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Delete specified file from document directory
提问by Anil Varghese
I want to delete an image from my app document directory. Code I have written to delete image is:
我想从我的应用程序文档目录中删除一个图像。我写的删除图像的代码是:
-(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];
}
Its working partially. This code deleting file from directory, but when I'm checking for the contents in directory, it still showing the image name there. I want to completely remove that file from directory. What should I change in the code to do the same? Thanks
它的部分工作。这段代码从目录中删除文件,但是当我检查目录中的内容时,它仍然在那里显示图像名称。我想从目录中完全删除该文件。我应该在代码中更改什么来做同样的事情?谢谢
回答by Anil Varghese
I checked your code. It's working for me. Check any error you are getting using the modified code below
我检查了你的代码。它对我有用。使用以下修改后的代码检查您遇到的任何错误
- (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]);
}
}
回答by Roman Barzyczak
Swift 3.0:
斯威夫特 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)
}}
Thanks to @Anil Varghese, I wrote very similiar code in swift 2.0:
感谢@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)
}
}
回答by FreeGor
Swift 2.0:
斯威夫特 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")
}
}
}
}
回答by Sai kumar Reddy
In Swift both 3&4
在 Swift 中 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)
}
}
orThis method can delete all local file
或者这个方法可以删除所有本地文件
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)")
}
}
回答by Chris Loonam
Instead of having the error set to NULL, have it set to
与其将错误设置为 NULL,不如将其设置为
NSError *error;
[fileManager removeItemAtPath:filePath error:&error];
if (error){
NSLog(@"%@", error);
}
this will tell you if it's actually deleting the file
这会告诉你它是否真的在删除文件
回答by user3182143
I want to delete my sqlite db from document directory.I delete the sqlite db successfully by below answer
我想从文档目录中删除我的 sqlite db。我通过以下答案成功删除了 sqlite db
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");
}
}
回答by Alex Spencer
NSError *error;
[[NSFileManager defaultManager] removeItemAtPath:new_file_path_str error:&error];
if (error){
NSLog(@"%@", error);
}
回答by Andrea Leganza
FreeGor version converted to Swift 3.0
FreeGor 版本转换为 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")
}
}
}
}
回答by Azon
If you are interesting in modern api way, avoiding NSSearchPath and filter files in documents directory, before deletion, you can do like:
如果您对现代 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 { let killFile = NSFileManager.defaultManager()
if (killFile.isDeletableFileAtPath(PathName)){
do {
try killFile.removeItemAtPath(arrayDictionaryFilePath)
}
catch let error as NSError {
error.description
}
}
as? URL }
.filter { ##代码##.pathExtension == "exe" }
for url in urls {
do {
try fileManager.removeItem(at: url)
} catch {
assertionFailure("\(error)")
}
}
回答by Mountain Man
You can double protect your file removal with NSFileManager.defaultManager().isDeletableFileAtPath(PathName) As of now you MUST use do{}catch{} as the old error methods no longer work. isDeletableFileAtPath() is not a "throws" (i.e. "public func removeItemAtPath(path: String) throws") so it does not need the do...catch
您可以使用 NSFileManager.defaultManager().isDeletableFileAtPath(PathName) 双重保护您的文件删除。到目前为止,您必须使用 do{}catch{},因为旧的错误方法不再有效。isDeletableFileAtPath() 不是“throws”(即“public func removeItemAtPath(path: String) throws”)所以它不需要 do...catch
##代码##