Ios 从文档目录中删除指定的文件
我想从我的应用程序文档目录中删除图像。我为删除图像而编写的代码是:Ios 从文档目录中删除指定的文件,ios,objective-c,xcode,nsdocumentdirectory,Ios,Objective C,Xcode,Nsdocumentdirectory,我想从我的应用程序文档目录中删除图像。我为删除图像而编写的代码是: -(void)removeImage:(NSString *)fileName { fileManager = [NSFileManager defaultManager]; paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); documentsPath = [paths obj
-(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];
}
它部分地起作用了。这段代码将文件从目录中删除,但当我检查目录中的内容时,它仍然会在目录中显示图像名称。我想从目录中完全删除该文件。我应该在代码中更改什么以执行相同的操作?谢谢,不要将错误设置为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]);
}
}
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()双重保护您的文件删除。从现在起,您必须使用do{}catch{},因为旧的错误方法不再有效。 IsDeleteTableFileAtPath()不是“抛出”(即。 “公共函数removietematpath(路径:字符串)抛出”) 所以它不需要做…捕捉
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版本已转换为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")
}
}
}
}
在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)
}
}
或
此方法可以删除所有本地文件
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)")
}
}
它可能会抛出一个您忽略的错误,添加NSError实例并在removeItemAtPathuse-(BOOL)fileExistsAtPath:(NSString*)路径后检查它;要检查映像是否存在,如果返回“是”,则表示您的删除失败。只需测试它,它肯定会被删除,并且删除会反映在目录路径的
内容中(即此处不涉及目录缓存)。因此,当您查看NSError
内容时,您一定会发现一些简单的错误。我可以在文档目录中创建文件,但在尝试删除它时总是会出错。你有什么想法吗?我解决了。问题是:我创建了一个没有任何属性的新文件,据我所知,它给出了一个默认属性NSFileImmutable YES。或者类似的。抱歉,现在无法显示来源。但问题很简单。是否有必要检查文件是否存在?它会从目录中删除文件,但仍在模拟器的照片中显示图像。为什么要将函数设置为静态?这取决于您。没有必要在调用函数之前/之后检查文件是否仍然存在以确保其已被删除?是的,确定:如果fileManager.fileExists(atPath:filePath!){print(“文件可用”)}否则{print(“文件不可用”)}以上Swift 3.0版本在Swift 5.2上运行良好。非常感谢。在最后一行添加以下内容以直接重试。do{try filemanager.removietem(atPath:destinationPath)print(“Deleted”)}catch{print(“notdeleted”)}
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)")
}
}