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]
Related
I'm trying to delete a csv file while deleting a cell, But I'm getting the next error when I pressed delete:
Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 3 beyond bounds [0 ..
2]'
* First throw call stack:
Code:
//
/
/ CameraViewController.m
// oFiOSstoryboard
//
// Created by Dorald on 24/05/15.
//
//
#import "CameraViewController.h"
#import "resultsDetailView.h"
#interface CameraViewController ()
#property (strong, nonatomic) IBOutlet UITableView *data;
#property (retain, nonatomic) IBOutlet UILabel *timeStamp;
#property (strong,nonatomic) NSMutableArray *dirList;
#property (nonatomic, assign) NSString *csvRow;
#property (nonatomic, strong) NSMutableArray *dataArray;
- (IBAction)didTapDeleteBtn:(id)sender;
#end
////////////////////////csv readder
NSMutableArray *tableDataArray;
NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
NSFileManager *manager = [NSFileManager defaultManager];
NSDirectoryEnumerator *direnum = [manager enumeratorAtPath:bundleRoot];
NSString *filename;
NSMutableArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *strPath = [[NSBundle mainBundle] pathForResource:#"file" ofType:#"csv"];
NSString *strFile = [NSString stringWithContentsOfFile:strPath encoding:NSUTF8StringEncoding error:nil];
NSMutableArray *timeStampb = [[NSMutableArray alloc] init]; ;
NSMutableArray *arrayToDelete = [[NSMutableArray alloc] init]; ;
NSMutableArray *filePathsArray ;
//NSMutableArray *dirList= [[NSMutableArray alloc] init]; ;
NSString *currentcsvfile;
NSString *csvfilenameSave;
#implementation CameraViewController
#synthesize data;
- (void)viewDidLoad {
[super viewDidLoad];
// ////lista de documentos
self.data.scrollEnabled = YES;
self.data.delegate = self;
self.data.dataSource = self;
//filePathsArray =[[NSMutableArray alloc] init]; ;
self.data.allowsMultipleSelectionDuringEditing = YES;
self.dataArray = [[NSMutableArray alloc]init];
NSInteger count = 100;
for (NSInteger i = count; i>=0; i--) {
NSString *title = [NSString stringWithFormat:#"cell %ld",i];
[self.dataArray addObject:title];
}
NSMutableArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *manager = [NSFileManager defaultManager];
NSMutableArray* fileList = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil];
//--- Listing file by name sort
NSLog(#"\n File list %#",fileList);
//---- Sorting files by extension
NSMutableArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF EndsWith '.csv'"];
filePathsArray = [filePathsArray filteredArrayUsingPredicate:predicate];
NSLog(#"\n\n Sorted files by extension %#",filePathsArray);
self.dirList = [filePathsArray mutableCopy];
NSString *docPath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
if (!strFile) {
NSLog(#"Error reading file.");
}
[timeStampb release];
timeStampb = [[NSMutableArray alloc] initWithArray:[strFile componentsSeparatedByString:#"\,"]];
// this .csv file is seperated with new line character
// if .csv is seperated by comma use "," instesd of "\n"
for(NSString *countryname in timeStampb) {
NSLog(#"%#", timeStampb);
}
}
////////////////////////////////////////////////////////////////Delete csv files
//- (IBAction)delet:(id)sender {
// NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
//
// NSString *filePath = [docPath stringByAppendingPathComponent:#"jorge.csv"];
// NSError *error = nil;
// [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
//}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
# pragma – mark table view DataSource Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.dirList count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier ];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
UIColor* color = [UIColor colorWithRed:(254.0/255.0) green:(251.0/255.0) blue:(248.0/255.0) alpha:1];
UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor colorWithRed:(253.0/255.0) green:(0.0/255.0) blue:(237.0/255.0) alpha:1];
[cell setSelectedBackgroundView:bgColorView];
cell.backgroundColor = color;
}
cell.textLabel.text = [timeStampb objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [self.dirList objectAtIndex:indexPath.row];
cell.textLabel.textColor = [UIColor colorWithRed:(0.0/255.0) green:(0.0/255.0) blue:(0.0/255.0) alpha:1];
cell.textLabel.font=[UIFont systemFontOfSize:8.0];
cell.detailTextLabel.font=[UIFont systemFontOfSize:15.0];
cell.detailTextLabel.textColor = [UIColor colorWithRed:(235.0/255.0) green:(120.0/255.0) blue:(33.0/255.0) alpha:1];
return cell;
}
-(UITableViewCell *)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"%d", indexPath.row);
currentcsvfile = [self.dirList objectAtIndex:indexPath.row ];;
csvfilenameSave = [NSString stringWithFormat:currentcsvfile];
NSArray *paths3 = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory3 = [paths3 objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/currentcsvnamefile.txt",
documentsDirectory3];
//create content - four lines of text
NSString *content =csvfilenameSave;
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy error:nil];
[_dirList addObject:_dirList[indexPath.row]];
NSLog(#"\n current csv csvfilenameSave % ",csvfilenameSave);
//[self performSegueWithIdentifier:#"detailsegue" sender:self];
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Update the delete button's title based on how many items are selected.
[_dirList removeObject:_dirList[indexPath.row]];
}
-(UITableViewCellEditingStyle)data:(UITableView *)data editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if ( editingStyle== UITableViewCellEditingStyleDelete) {
[self.data deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[data setEditing:NO animated:YES];
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *filePath = [docPath stringByAppendingPathComponent:[self.dirList objectAtIndex:indexPath.row ]];
NSError *error = nil;
[[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
[_dirList removeObjectAtIndex:indexPath.row];
}
}
#pragma mark - UITableView Delegate Methods
//- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
//{
// return UITableViewCellEditingStyleDelete;
//}
#pragma mark - Delete Button Action
#pragma mark – TableView delegate
- (void)dealloc {
[_timeStamp release];
[self.dirList release];
self.data.delegate = nil;
self.data.dataSource = nil;
[super dealloc];
}
#end
Actually what you are doing you are removing the value from array at the top. You have to remove the value from array at the end of this function. As i have done in below code, please check my answer and use this code and then tell me if you face any issue. I Update my answer Please check it again.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if ( editingStyle== UITableViewCellEditingStyleDelete) {
currentcsvfile = [self.dirList objectAtIndex:indexPath.row];
csvfilenameSave = [NSString stringWithFormat:currentcsvfile];
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *filePath = [docPath stringByAppendingPathComponent:csvfilenameSave];
NSError *error = nil;
[[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
[_dirList removeObjectAtIndex:indexPath.row];
[self.data beginUpdates];
[self.data deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.data endUpdates];
[data setEditing:NO animated:YES];
}
}
Call to method [self.data deleteRowsAtIndexPaths:withRowAnimation:]; sends a message to the table view to adjust its presentation and thus tableview throws an NSInternalInconsistencyException because _dirList count is not equal to tableviews row count.
For details look at this article Inserting and Deleting Rows and Sections
You can handle this by removing the item corresponding to
the row from _dirList array at first and then sending deleteRowsAtIndexPaths:withRowAnimation: to the table view.
Try to replace below lines of code inside - (void)tableView:(UITableView *)tableView commitEditingStyle method:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if ( editingStyle== UITableViewCellEditingStyleDelete) {
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *filePath = [docPath stringByAppendingPathComponent:[self.dirList objectAtIndex:indexPath.row ]];
NSError *error = nil;
[[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
[_dirList removeObjectAtIndex:indexPath.row];
[self.data deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
Hope it will work!
I want to attach csv files created in my app to an email by selecting the files listed in UITableView.
I have all the files listed in my UITableView and am able to attach single selected files to an email without any issue however for the life of me i cannot figure out how to attach multiple files i have selected within the UITableView.
I am storing the selected files in an NSMutableArray called selectedData.
How would i go about doing this? I have been searching for an answer for a while now but have found nothing directly related to what i am trying to do.
here is my code so far:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [filePathsArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MainCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"MainCell"];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
NSPredicate *fltr = [NSPredicate predicateWithFormat:#"self ENDSWITH '.csv'"];
NSArray *csvFiles = [fileList filteredArrayUsingPredicate:fltr];
NSLog(#"Contents of directory: %#", csvFiles);
filePathsArray = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:documentsDirectory error:nil];
cell.textLabel.text = [csvFiles objectAtIndex:indexPath.row];
return cell;
}
# pragma mark - Deleting data from Row.
- (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 {
{
NSString *fileName = [filePathsArray objectAtIndex:indexPath.row];
NSString *path;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
path = [paths objectAtIndex:0];
path = [path stringByAppendingPathComponent:fileName];
NSError *error;
[filePathsArray removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView reloadData];
if ([[NSFileManager defaultManager]fileExistsAtPath:path]) {
if(![[NSFileManager defaultManager] removeItemAtPath:path error:&error])
{
NSLog(#"Delete file error:%#", error);
}
NSLog(#"Deleting file named: %#", path);
}
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryNone) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[self.selectedData addObject:[filePathsArray objectAtIndex:indexPath.row]];
NSLog(#"selectedData %#",self.selectedData);
}
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
cell.accessoryType = UITableViewCellAccessoryNone;
[self.selectedData removeObject:[filePathsArray objectAtIndex:indexPath.row]];
NSLog(#"deselectedData %#",self.selectedData);
}
}
#pragma mark - Email Selected Data
-(IBAction)emailButton:(id)sender
{
}
- (void)showEmail:(NSString*)file {
NSString *emailTitle = #"Your Data";
NSString *messageBody = #"Attached is your recorded data.";
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setMessageBody:messageBody isHTML:NO];
// Determine the file name and extension
NSArray *filepart = [file componentsSeparatedByString:#"."];
NSString *filename = [filepart objectAtIndex:0];
NSString *extension = [filepart objectAtIndex:1];
// Get the resource path and read the file using NSData
NSString *filePath = [[NSBundle mainBundle] pathForResource:filename ofType:extension];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
// Determine the MIME type
NSString *mimeType;
if ([extension isEqualToString:#"csv"]) {
mimeType = #"text/csv";
}
// Add attachment
[mc addAttachmentData:fileData mimeType:mimeType fileName:filename];
// Present mail view controller on screen
[self presentViewController:mc animated:YES completion:NULL];
}
- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
switch (result)
{
case MFMailComposeResultCancelled:
NSLog(#"Mail cancelled");
break;
case MFMailComposeResultSaved:
NSLog(#"Mail saved");
break;
case MFMailComposeResultSent:
NSLog(#"Mail sent");
break;
case MFMailComposeResultFailed:
NSLog(#"Mail sent failure: %#", [error localizedDescription]);
break;
default:
break;
}
// Close the Mail Interface
[self dismissViewControllerAnimated:YES completion:NULL];
}
Any and all help would be greatly appreciated.
Try something like this.
Assuming all files are of the same mime-type csv.
And assuming that all file names in self.selectedData have a structure like "myfile.csv".
- (void)showEmail {
NSString *emailTitle = #"Your Data";
NSString *messageBody = #"Attached is your recorded data.";
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setMessageBody:messageBody isHTML:NO];
for (NSString *file in self.selectedData) {
// Determine the file name and extension
NSArray *filepart = [file componentsSeparatedByString:#"."];
NSString *filename = [filepart objectAtIndex:0];
NSString *extension = [filepart objectAtIndex:1];
// Get the resource path and read the file using NSData
NSString *filePath = [[NSBundle mainBundle] pathForResource:filename ofType:extension];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
// Determine the MIME type
NSString *mimeType;
if ([extension isEqualToString:#"csv"]) {
mimeType = #"text/csv";
}
// Add attachment
[mc addAttachmentData:fileData mimeType:mimeType fileName:filename];
}
// Present mail view controller on screen
[self presentViewController:mc animated:YES completion:NULL];
}
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]];
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.
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