Get images from documents directory to collection view - ios

How can I get images from documents directory to poplulate a collection view. So far I get all the images dumped into each cell according to my log, (or at least the image name is printed in the log)
First im getting the image names from the documents directory filelist is an NSMutable array of imageNames.png
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:nil];
fileList=[[NSMutableArray alloc]init];
for (NSString *filename in dirContents) {
NSString *fileExt = [filename pathExtension];
if ([fileExt isEqualToString:#"png"]) {
[fileList addObject:filename];
}
}
NSLog(#"document folder content list %# ",fileList);
This returns a list of my png file names in my NSMutsableArray fileList. Then I want to get all these images into my collection view
//set up cell from nib in viewDidLoad
UINib *cellNib = [UINib nibWithNibName:#"NibCell" bundle:nil];
[self.appliancesCollectionView registerNib:cellNib forCellWithReuseIdentifier:#"cvCell"];
/////
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return fileList.count;
NSLog(#"collection view count is %#",fileList);
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
// Setup cell identifier
static NSString *cellIdentifier = #"cvCell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
NSString *fileName = [fileList objectAtIndex:indexPath.row];
cell.backgroundView = [[UIImageView alloc] initWithImage: [UIImage imageNamed: fileName]];
NSLog(#"cell Bg image %#",fileList);
return cell;
}
The probelm is nothing shows up in my collection view cells

The problem is that contentsOfDirectoryAtPath returns relative file paths. And you need absolute. Something like following should be used:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:nil];
fileList=[[NSMutableArray alloc]init];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; // NEW LINE 1
for (NSString *filename in dirContents) {
NSString *fileExt = [filename pathExtension];
if ([fileExt isEqualToString:#"png"]) {
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:filename]; // NEW LINE 2
[fileList addObject:fullPath]; // NEW LINE 3
}
}
NSLog(#"document folder content list %# ",fileList);

You need to use imageWithContentsOfFile: instead imageNamed:
NSString * filePath = [[NSBundle mainBundle] pathForResource:<imageNameWithoutExtansion>ofType:<fileExtansion>];
cell.backgroundView = [[UIImageView alloc] initWithImage: [UIImage imageWithContentsOfFile: filePath]];

Related

Cannot delete picture

I am saving my pictures into the collection view but I cannot delete the picture that I have took. I am using tap delete in the collection view. This is my code for that.However after I tap and delete the picture it looks like the picture is not deleted, and cannot find where is wrong, I am suspecting that it has something to do with the array but I am not sure.
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
allImagesArray = [[NSMutableArray alloc] init];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *locations = [[NSArray alloc]initWithObjects:#"Bottoms", #"Dress", #"Coats", #"Others", #"hats", #"Tops",nil ];
NSString *fPath = documentsDirectory;
NSMutableArray *trashCan = [NSMutableArray array];
NSArray *directoryContent;
for(NSString *component in locations){
NSString *TrashBin = [fPath stringByAppendingPathComponent:component];
NSArray *directoryContent = [[NSFileManager defaultManager] directoryContentsAtPath: TrashBin];
collectionTrash.delegate =self;
collectionTrash.dataSource=self;
for(NSString *str in directoryContent){
NSLog(#"str:%#", str);
NSString *finalFilePath = [TrashBin stringByAppendingPathComponent:str];
NSData *data = [NSData dataWithContentsOfFile:finalFilePath];
[trashCan addObject:finalFilePath];
if(data)
{
UIImage *image = [UIImage imageWithData:data];
[allImagesArray addObject:image];
NSLog(#"array:%#",[allImagesArray description]);
}}}
Trash = trashCan;
for(NSString *folder in locations) {
for(NSString *file in directoryContent) {
// load the image
}
}}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
NSLog(#"j");
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [allImagesArray count];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *reuseID = #"ReuseID";
TrashCell *mycell = (TrashCell *) [collectionView dequeueReusableCellWithReuseIdentifier:reuseID forIndexPath:indexPath];
UIImageView *imageInCell = (UIImageView*)[mycell viewWithTag:1];
imageInCell.image = [allImagesArray objectAtIndex:indexPath.row];
NSLog(#"a");
return mycell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
NSLog(#"s:%d", [Trash count]);
NSString *trashBin = [Trash objectAtIndex:indexPath.row];
NSLog(#"k%#l",trashBin);
[allImagesArray removeObjectAtIndex:indexPath.row];
[self.collectionTrash reloadData];
[self deleteMyFiles:trashBin];
}
NSString *myFileName;
-(void) deleteMyFiles:(NSString*)filePath {
NSError *error;
if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
[[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
}
}
Be sure you delete the image in local memory also. When you delete image from collectionView not delete. Then stop the app and run it again see the deleted image is removed or not?. I think this is your problem. Then store all the image in single array and store it in plist. When you remove any image replace the array after removing the image in the array.
Use
[collectionView reloadData]
after calling deleteMyFiles.

Save image that is displayed in UIImage and categorize it

I want to save an image that is displayed in the UIImage. However I want to categorize it in genre for example vegetables, meat, lettuce, etc.
I cannot find a way to do that.
What is the best and easiest way to do this?
Also I want to make the user select which category he wants to save using the picker controller to save.
Thank you! I really need help!!
Update 2
To check if it is saved I went further to construct a collection View controller and I get errors saying at the images part at the [arrayCollectionImages addObject:image]; Can you explain me about this last piece of code. I also have an warning at arrayCollectionImages saying local declaration of arrayColectionImages hide instance variable. –
#interface CollectionViewController (){
NSArray *arrayCollectionImages;
}
#end
#implementation CollectionViewController
- (void)viewDidLoad {
dispatch_queue_t searchQ = dispatch_queue_create("com.awesome", 0);
dispatch_async(searchQ, ^{
NSArray *arrayCollectionImages = [[NSArray alloc ]init];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *location=#"Hats";
NSString *fPath = [documentsDirectory stringByAppendingPathComponent:location];
NSArray *directoryContent = [[NSFileManager defaultManager] directoryContentsAtPath: fPath];
for(NSString *str in directoryContent){
NSString *finalFilePath = [fPath stringByAppendingPathComponent:str];
NSData *data = [NSData dataWithContentsOfFile:finalFilePath];
if(data)
{ dispatch_async(dispatch_get_main_queue(),^{
UIImage *image = [UIImage imageWithData:data];
});
[arrayCollectionImages addObject:images];
}
}
});
[super viewDidLoad];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"ReuseID" forIndexPath:indexPath];
[[cell collectionImageView]setImage:[UIImage imageNamed:[arrayCollectionImages objectAtindex:indexPath.item]]];
return cell;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return [arrayCollectionImages count];
}
#end
Step 1:
Set up a Picker Controller.
Here is the official reference.
Here is a tutorial.
Try to set it with all the genre values you want. You will learn about its delegate method:
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
that will return the genre selected.
Step 2:
Provide a save icon or a save button on each image. On click of that icon/button you should make your picker view appear and make user select any row and the image should be copied to a private variable or a property here, so as to refer it later in the delegate method.
Step 3:
When user selects a row, this delegate method is called. Here we will create a new directory , if not already exists, according to the genre selected In UIPickerView. Then you should write your image to the path.
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//fetch Category Name from the array used to fill the Picker View
NSString *categoryName= [array objectAtIndex:row];
NSString *fPath = [documentsDirectory stringByAppendingPathComponent:categoryName];
NSFileManager *fileManager=[[NSFileManager alloc]init];
[fileManager createDirectoryAtPath:fPath withIntermediateDirectories:YES attributes:NO error:NO];
UIImage *image= captureImage;
NSData *data= UIImagePNGRepresentation(image);
[data writeToFile:fPath atomically:NO];
}
To retrieve images from a particular folder in your documents directory:
Create a path to that folder first. This will depend on a particular genre. Let's say Genre1.
// An array to save all images. You have to do this in some other way if selected images are big in size.
// For that case I suggest retrieving of images only when you are showing them on screen.
NSArray *allImagesArray = [[NSArray alloc ]init];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *location=#"Genre1";
NSString *fPath = [documentsDirectory stringByAppendingPathComponent:location];
NSArray *directoryContent = [[NSFileManager defaultManager] directoryContentsAtPath: fPath];
for(NSString *str in directoryContent){
NSString *finalFilePath = [fPath stringByAppendingPathComponent:str];
NSData *data = [NSData dataWithContentsOfFile:finalFilePath];
if(data)
{
UIImage *image = [UIImage imageWithData:data];
[allImagesArray addObject:image];
}
}

Error when recalling directory to Collection View

I am using this code to recall the directory that I have made for each genre. However I get errors saying at the images part at the [arrayCollectionImages addObject:image]; Can you explain what is wrong with the last piece of code. I also have an warning at arrayCollectionImages saying local declaration of arrayColectionImages hide instance variable. It is also telling me that the [[cell collectionImageView]setImage:[UIImage imageNamed:[arrayCollectionImages objectAtindex:indexPath.item]]]; No visible #interface for "NSArray" declares the selector "objectAtindex:;" What did I have done wrong?
#import "CollectionViewController.h"
#import "CollectionCell.h"
#interface CollectionViewController (){
NSArray *arrayCollectionImages;
}
#end
#implementation CollectionViewController
- (void)viewDidLoad {
NSArray *allImagesArray = [[NSArray alloc ]init];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *location=#"Genre1";
NSString *fPath = [documentsDirectory stringByAppendingPathComponent:location];
NSArray *directoryContent = [[NSFileManager defaultManager] directoryContentsAtPath: fPath];
for(NSString *str in directoryContent){
NSString *finalFilePath = [fPath stringByAppendingPathComponent:str];
NSData *data = [NSData dataWithContentsOfFile:finalFilePath];
if(data)
{
UIImage *image = [UIImage imageWithData:data];
[allImagesArray addObject:image];
}
}
[super viewDidLoad];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"ReuseID" forIndexPath:indexPath];
[[cell collectionImageView]setImage:[UIImage imageNamed:[arrayCollectionImages objectAtIndex:indexPath.item]]];
return cell;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return [arrayCollectionImages count];
}
#end
This is my code for saving to directory
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
FrontCamera = NO;
cameraSwitch.selectedSegmentIndex = 1;
captureImage.hidden = YES;
[pickerViewContainer addSubview:SaveTopicker];
arraygenre = [[NSMutableArray alloc] init];
[arraygenre addObject:#"Tops"];
[arraygenre addObject:#"Pants"];
[arraygenre addObject:#"Coats"];
[arraygenre addObject:#"Shoes"];
[arraygenre addObject:#"Hats"];
[arraygenre addObject:#"Others"];
pickerViewContainer.frame = CGRectMake(0, 800, 320, 261);
}
- (void)viewDidAppear:(BOOL)animated {
[self initializeCamera];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//fetch Category Name from the array used to fill the Picker View
NSString *categoryName= [arraygenre objectAtIndex:row];
NSString *fPath = [documentsDirectory stringByAppendingPathComponent:categoryName];
NSFileManager *fileManager=[[NSFileManager alloc]init];
[fileManager createDirectoryAtPath:fPath withIntermediateDirectories:YES attributes:nil error:nil];
UIImage *image = captureImage.image;
NSData *data = UIImagePNGRepresentation(image);
[data writeToFile:fPath atomically:YES];
}
The method name is objectAtIndex:. You have the "i" in the method name in lower case which is incorrect.

Image on UITableView Cell

i have different folder on document directory and have images on each folder. Now i want to display one image from different folder. i have tried but the program is crashe at the line.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
//I dont know what put here for display from sqlite
NSUInteger row = [indexPath row];
cell.textLabel.text = [array1 objectAtIndex:row];
//cell.detailTextLabel.text = [array2 objectAtIndex:row];
NSString *b = [array2 objectAtIndex:row];
NSLog(#"b=%#",b);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(#"%#",paths);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSError *error = nil;
NSArray *imageFileNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#",b]] error:&error];
NSLog(#"file=%#",imageFileNames);
NSMutableArray *images = [[NSMutableArray alloc ] init];
for (int i = 0; i < [imageFileNames count]; i++)
{
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#/%d.png",b, i]];
UIImage *img = [UIImage imageWithContentsOfFile:getImagePath];
[images addObject:img];
NSLog(#"%#",getImagePath);
}
NSLog(#"images=%#",images);
cell.imageView.image=[imageFileNames objectAtIndex:0];
//NSLog(#"row=%u",row);
return cell;
}
I think what you are looking at is something like this (please modify to your liking):
NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
self.contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documents error:NULL];
...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.fileLabel.text = [self.contents objectAtIndex:indexPath.row];
// Build Documents Path with Folder Name
NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *directory = [documents stringByAppendingPathComponent:[self.contents objectAtIndex:indexPath.row]];
NSFileManager *fM = [NSFileManager defaultManager];
// Get Attributes
NSDictionary *fileAttributes = [fM attributesOfItemAtPath:directory error:NULL];
// Check if it's a directory
if ([fileAttributes objectForKey:NSFileType] == NSFileTypeDirectory) {
// Get contents of directory
NSArray *insideDirectory = [fM contentsOfDirectoryAtPath:directory error:NULL];
cell.folderImageView.image = nil;
// Loop through folder contents
for (NSString *file in insideDirectory) {
if ([[[file pathExtension] uppercaseString] isEqualToString:#"PNG"]) {
NSString *imagePath = [directory stringByAppendingPathComponent:file];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
cell.imageView.image = image;
break;
}
}
}
return cell;
}
You can directly use [UIImage imageNamed:#""] for images rather than imageWithContentsOfFile

Deleting files from local app Documents folder

So far I have managed to delete rows from my table view but it won't update in the given Documents folder. How would I achieve this? Below is the code I'm using.
I tried to implement the code from here How to delete files from a folder which is placed in documents folder.
My goal is to have the ability to delete any file, not just a desired file.
Thanks in advance.
#import "Documents.h"
#interface DocumentsViewController ()
#end
#implementation DocumentsViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
self.navigationItem.rightBarButtonItem = self.editButtonItem;
NSString *temp = [[NSBundle mainBundle] resourcePath];
self.directoryPath = [temp stringByAppendingPathComponent:#"Documents"];
[self.tableView setEditing:NO animated:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [directoryContents count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
cell.textLabel.text = [directoryContents objectAtIndex:indexPath.row];
return cell;
}
-(NSString*)directoryPath{
return directoryPath;
}
-(void)setDirectoryPath:(NSString*)a{
[a retain];
[directoryPath release];
directoryPath = a;
[self loadDirectoryContents];
[table reloadData];
}
-(void)loadDirectoryContents{
[directoryContents release];
directoryContents = [[NSFileManager defaultManager] directoryContentsAtPath: directoryPath];
[directoryContents retain];
}
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { //implement the delegate method
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Update data source array here, something like [array removeObjectAtIndex:indexPath.row];
[directoryContents removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView reloadData];
NSString *extension = #"png";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:NULL];
NSEnumerator *e = [contents objectEnumerator];
NSString *filename;
while ((filename = [e nextObject])) {
if ([[filename pathExtension] isEqualToString:extension]) {
[fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];
}
}
}
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
*/
}
-(void)dealloc{
[super dealloc];
[directoryContents release];
directoryContents = nil;
self.directoryPath = nil;
[table release];
table = nil;
}
#end
WORKING CODE FOR ME:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
if (editingStyle == UITableViewCellEditingStyleDelete){
NSString *fileName = [directoryContents objectAtIndex:indexPath.row];
NSString *path;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
path = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"downloads"];
path = [path stringByAppendingPathComponent:fileName];
NSError *error;
//Remove cell
[directoryContents removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
[tableView reloadData];
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) //Does file exist?
{
if (![[NSFileManager defaultManager] removeItemAtPath:path error:&error]) //Delete it
{
NSLog(#"Delete file error: %#", error);
}
}
}
}
NSFileManager is very useful in removing files:
[[NSFileManager defaultManager] removeItemAtPath: pathToFile error: &error];
Also take a look at this article it has some useful codes. Although a bit old but the codes works just fine.
http://iphonedevsdk.com/forum/iphone-sdk-development/3576-how-do-i-delete-a-file-in-my-documents-directory.html
Here is some more code example
// Get the Documents directory path
NSString *temPath = [NSString stringWithFormat:#"%#%d",#"Documents/Media_", Key_mediaID];
//This temPath look line ../../../Documents/Media_1
NSString *documentsDirectoryPath = [NSHomeDirectory() stringByAppendingPathComponent:temPath];
// Delete the file using NSFileManager
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:[documentsDirectoryPath stringByAppendingPathComponent:Your File Name] error:nil];
Here is another link with some more helpful code
http://ios.biomsoft.com/2012/01/17/delete-all-files-in-documents-directory/
Hope this helps you out.
Edit:
To remove a files with specific extension say for example jpg you can try the following
NSString *extension = #"jpg";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:NULL];
NSEnumerator *e = [contents objectEnumerator];
NSString *filename;
while ((filename = [e nextObject])) {
if ([[filename pathExtension] isEqualToString:extension]) {
[fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];
}
}
In addition to the above if you know the path to the file you want to delete the following is a useful code:
// Get the Documents directory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
// Delete the file using NSFileManager
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:[documentsDirectoryPath stringByAppendingPathComponent:yourFile.txt] error:nil];
Edit 2:
To delete the document in a specific folder:
NSError *error;
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documents= [documentsDirectory stringByAppendingPathComponent:#"YourFolder"];
NSString *filePath = [documents stringByAppendingPathComponent:#"file2.txt"];
[fileMgr removeItemAtPath:filePath error:&error]

Resources