ios objective-c xcode nsdocumentdirectory

ios - Eliminar el archivo especificado del directorio del documento



objective-c xcode (9)

En lugar de tener el error establecido en NULL, configúrelo para

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

esto le dirá si realmente está borrando el archivo

Quiero eliminar una imagen del directorio de documentos de mi aplicación. El código que he escrito para borrar la imagen es:

-(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]; }

Está trabajando parcialmente. Este código borra el archivo del directorio, pero cuando estoy buscando los contenidos en el directorio, sigue mostrando el nombre de la imagen allí. Quiero eliminar completamente ese archivo del directorio. ¿Qué debería cambiar en el código para hacer lo mismo? Gracias


Puede proteger doblemente su eliminación de archivos con NSFileManager.defaultManager (). IsDeletableFileAtPath (PathName) A partir de ahora DEBE usar do {} catch {} ya que los métodos de error anteriores ya no funcionan. isDeletableFileAtPath () no es un "throws" (es decir, "public func removeItemAtPath (path: String) throws") por lo que no necesita el do ... catch

let killFile = NSFileManager.defaultManager() if (killFile.isDeletableFileAtPath(PathName)){ do { try killFile.removeItemAtPath(arrayDictionaryFilePath) } catch let error as NSError { error.description } }


Quiero eliminar mi sqlite db del directorio del documento. Borro el sqlite db con éxito por debajo de la respuesta

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"); } }


Revisé tu código. Está funcionando para mí. Verifique cualquier error que esté recibiendo usando el código modificado a continuación

- (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]); } }


Si eres interesante en una forma moderna de api, evitando NSSearchPath y filtrando archivos en el directorio de documentos, antes de borrarlos, puedes hacer lo siguiente:

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)") } }


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") } } } }


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) }}

Gracias a @Anil Varghese, escribí un código muy similar en 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) } }


Versión de FreeGor convertida a 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") } } } }


NSError *error; [[NSFileManager defaultManager] removeItemAtPath:new_file_path_str error:&error]; if (error){ NSLog(@"%@", error); }