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.
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 am developing an app that will display data from server in a parallax type UITableView, and here is my code. Everything is loading great, but cell data(image, etc) keep switching from one cell to another.
- (void)viewDidLoad
{
[self hasInternet];
self.tableView.dataSource = self;
self.tableView.delegate = self;
[self loadData];
self.edgesForExtendedLayout=UIRectEdgeNone;
self.extendedLayoutIncludesOpaqueBars=NO;
self.automaticallyAdjustsScrollViewInsets=NO;
[super viewDidLoad];
}
- (void)viewWillAppear:(BOOL)animated
{
[self scrollViewDidScroll:nil];
[super viewWillAppear:animated];
[self loadData];
self.tableView.dataSource = self;
self.tableView.delegate = self;
}
- (void) loadData{
name = #"name";
email = #"email";
thumbnail = #"thumbnail";
myObject = [[NSMutableArray alloc] init];
NSData *jsonSource = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://URL.php"]];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonSource options:NSJSONReadingMutableContainers error:nil];
for (NSDictionary *dataDict in jsonObjects) {
NSString *title_data = [dataDict objectForKey:#"fname"];
NSString *title_data2 = [dataDict objectForKey:#"lname"];
NSString *fulname = [NSString stringWithFormat:#"%# %#", title_data, title_data2];
NSString *emAil = [dataDict objectForKey:#"email"];
NSString *thumbnail_data = [dataDict objectForKey:#"img"];
thumbnail_data = [NSString stringWithFormat:#"http://URL/upload/%#",thumbnail_data];
dictionary = [NSDictionary dictionaryWithObjectsAndKeys: fulname, name, emAil, email, thumbnail_data, thumbnail, nil];
[myObject addObject:dictionary];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return myObject.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"parallaxCell";
JBParallaxCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell=[[JBParallaxCell alloc]initWithStyle:
UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
NSDictionary *tmpDict = [myObject objectAtIndex:indexPath.row];
NSMutableString *text;
text = [NSMutableString stringWithFormat:#"%#",[tmpDict objectForKeyedSubscript:name]];
NSMutableString *mail;
mail = [NSMutableString stringWithFormat:#"%#",[tmpDict objectForKeyedSubscript:email]];
NSMutableString *images;
images = [NSMutableString stringWithFormat:#"%# ",[tmpDict objectForKey:thumbnail]];
NSURL *url = [NSURL URLWithString:[tmpDict objectForKey:thumbnail]];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL *url = [NSURL URLWithString:[tmpDict objectForKey:thumbnail]];
NSData *data = [NSData dataWithContentsOfURL:url];
dispatch_async(dispatch_get_main_queue(), ^{
cell.parallaxImage.image = [[UIImage alloc]initWithData:data];
});
});
cell.titleLabel.text = [NSString stringWithFormat:#"%#",text];
cell.subtitleLabel.text = [NSString stringWithFormat:#"%#",mail];
return cell;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
NSArray *visibleCells = [self.tableView visibleCells];
for (JBParallaxCell *cell in visibleCells) {
[cell cellOnTableView:self.tableView didScrollOnView:self.view];
}
}
When I compile it, it shows all my data but then keep switching from one cell to another. Any help will be appreciated. Thanks
Because UITableView reuse the cell so when you scroll down or up the previous cell which is gone from your tableview bound is reuse. but it's image view has an image when it use last time so you have to clear first the imageview.
so put this line
cell.parallaxImage.image = nil;
Before the dispatch queue
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
You can use this code it will save the images in document directry and then show it.
please change the variable name.
NSString *imageURL = [[matcheListArr objectAtIndex:indexPath.row] valueForKey:#"thumbnail_image"];
NSURL *url = [NSURL URLWithString:imageURL];
NSArray *seperate = [[[matcheListArr objectAtIndex:indexPath.row] valueForKey:#"thumbnail_image"] componentsSeparatedByString:#"/"];
NSString *fileName = [NSString stringWithFormat:#"%#.png",[seperate objectAtIndex:seperate.count-1]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/MyFolder"];
NSError *error;
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
NSString *getImagePath = [dataPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#",fileName]];
UIImage *img = [UIImage imageWithContentsOfFile:getImagePath];
if ([img isKindOfClass:[UIImage class]]) {
//Set Downloaded Image
[cell.matchUserImageView setImage:img];
}
else {
if ([[ValidationString sharedManager] isNullString:[[matcheListArr objectAtIndex:indexPath.row] valueForKey:#"thumbnail_image"]] == YES) {
//Set Default Image
[cell.matchUserImageView setImage:[UIImage imageNamed:#"photo_icon.png"]];
}
else{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
NSData *imageData = [NSData dataWithContentsOfURL:url];
NSArray *seperate = [[[matcheListArr objectAtIndex:indexPath.row] valueForKey:#"thumbnail_image"] componentsSeparatedByString:#"/"];
NSString *fileName = [NSString stringWithFormat:#"%#.png",[seperate objectAtIndex:seperate.count-1]];
dispatch_async(dispatch_get_main_queue(), ^{
// Update the UI
[cell.matchUserImageView setImage:[UIImage imageWithData:imageData]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/MyFolder"];
NSString *savedImagePath = [dataPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#",fileName]];
[imageData writeToFile:savedImagePath atomically:NO];
});
});
}
}
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