I have a list of images in my resources folder that I want to load into a collection view
I have my images file names in an NSAarray from the documents directory.
.h
{
NSArray *fileList;
NSString * searchedImage;
}
.m
NSFileManager *filesm = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSArray *getFilelist= [filesm contentsOfDirectoryAtPath:[paths objectAtIndex:0] error:nil];
BOOL isDirectory;
for (searchedImage in getFilelist){
BOOL fileExistsAtPath = [[NSFileManager defaultManager] fileExistsAtPath:searchedImage isDirectory:&isDirectory];
if (fileExistsAtPath) {
if (isDirectory)
{
//Found Directory
}
}
if ([[searchedImage pathExtension] isEqualToString:#"png"]) {
//This is Image File with .png Extension
NSLog(#"directoryContents = %#",searchedImage);
}
}
//count files
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *pathsAmount = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
fileList= [fm contentsOfDirectoryAtPath:[pathsAmount objectAtIndex:0] error:nil];
int filesCount = [fileList count];
NSLog(#"filesCount:%d", filesCount);
UINib *cellNib = [UINib nibWithNibName:#"NibCell" bundle:nil];
[self.appliancesCollectionView registerNib:cellNib forCellWithReuseIdentifier:#"cvCell"];
}
return self;
}
this reurns my image names correctly as 63293446.png, appliance63293447.png, appliance63293448.png, appliance63293449.png, etc in viewDidLoad
I want to load these into my collection view cells. Currently it returns a null value for my images file names when in the -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath method
What ive tried so far in addtion to researching on here
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return fileList.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"cvCell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
cell.backgroundView = [[UIImageView alloc] initWithImage: [UIImage imageNamed: [NSString stringWithFormat:#"%#",searchedImage]]];
NSLog(#"cell Bg image %#",searchedImage); <-----------------//returns null
return cell;
}
try this code
cell.backgroundView = [[UIImageView alloc] initWithImage: [UIImage imageNamed: [NSString stringWithFormat:#"%#",[fileList objectAtIndex:indexPath.row]]]];
make sure searchedImage is not nil.
The file name of the image is in your fileList array, not in searchedImage, (this last variable is useless when creating the image).
NSString *fileName = [fileList objectAtIndex:indexPath.row];
cell.backgroundView = [[UIImageView alloc] initWithImage: [UIImage imageNamed: fileName]];
The problem here is that in your code, fileList can contain files that are not images, thus imageNamed: will fail, and return nil. You should filter your fileList array, and make sure it contains only images.
At first make fileList mutable via NSMutableArray *fileList;
next in block add image path to fileList
if ([[searchedImage pathExtension] isEqualToString:#"png"]) {
//This is Image File with .png Extension
NSLog(#"directoryContents = %#",searchedImage);
[fileList addObject:searchedImage]
}
then in cellForItemAtIndexPath: set image with
cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:[fileList objectAtIndex:indexPath.row]]];
Related
I'm trying to display image from documents directory in UICollectionView, everything works fine, but no image appears
- (void)viewDidLoad
{
[super viewDidLoad];
// Initialize recipe image array
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
NSMutableArray *image = [NSMutableArray array];
for (NSString *tString in dirContents) {
if ([tString hasSuffix:#".png"]) {
[image addObject:tString];
listeImages = [NSArray arrayWithArray:image];
}
}
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return listeImages.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = #"Cell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
UIImageView *listeImageView = (UIImageView *)[cell viewWithTag:100];
UILabel *LabelView = (UILabel *)[cell viewWithTag:110];
LabelView.text = [listeImages objectAtIndex:indexPath.row];
listeImageView.image = [UIImage imageNamed:[listeImages objectAtIndex:indexPath.row]];
NSLog(#" List UIImageView listeImageView.image %#",listeImageView.image);
cell.backgroundColor = [UIColor redColor];
cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"photo-frame.png"]];
NSLog(#" List NSArray *listeImages %#",listeImages);
cell.tag = indexPath.row;
return cell;
}
with this piece of code, displays the correct UICollectionView UILabel well but no image is displayed.
I use this line of code to store my image in listeImageView.image.
UIImageView *listeImageView = (UIImageView *)[cell viewWithTag:100];
listeImageView.image = [UIImage imageNamed:[listeImages objectAtIndex:indexPath.row]];
Here are the results of my NSLog:
2014-10-11 09:46:31.117 imgapp[2803:60b] List NSArray *listeImages; (
"image10102014233607.png",
"image10102014233616.png",
"image10102014233627.png"
)
2014-10-11 09:46:31.158 imgapp[2803:60b] List UIImageView listeImageView.image (null)
2014-10-11 09:46:31.171 imgapp[2803:60b] List UIImageView listeImageView.image (null)
2014-10-11 09:46:31.178 imgapp[2803:60b] List UIImageView listeImageView.image (null)
any help will be appreciated.
Thanks
You have below,
listeImageView.image = [UIImage imageNamed:[listeImages objectAtIndex:indexPath.row]];
But your doing,
cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"photo-frame.png"]];
Why your not using your listeImageView as below:-
cell.backgroundView = listeImageView;
That should get you the image.
UPDATE :-
for (NSString *tString in dirContents) {
if ([tString hasSuffix:#".png"]) {
**[image addObject:[UIImage imageWithContentsOfFile:tString] ]; //Do this as in below line you were not create a image object which you are trying to get.**
//Also check your image array for object, that is it getting stored or not.
// [image addObject:tString];
}
}
listeImages = [NSArray arrayWithArray:image]; //Do this after you have added all objects in your image mutable array and not in for loop as this will initialise it many tiems depending on your loop run count.
You're not adding your listeImageView to anything.
Try it with
[cell addSubview:listeImageView];
or if you really want it to be the backgroundView
cell.backgroundView = listeImageView;
But it'd be much cleaner if you create a custom UICollectionViewCell-class where you can define what content this cell has.
Have u tried to give background color to cell instead of backgroundview.do that once if possible with same code of yours!
Or
You can try like :-UIImageView *listeImageView = (UIImageView *)[cell viewWithTag:100];
[cell bringviewtoFront:listeImageView ];
You'd be much better off subclassing UICollectionViewCell, and setting up the subviews in a storyboard. Your code could be much cleaner this way:
static NSString *kCustomCellIdentifier = #"customcell";
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
MYAPPCustomCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCustomCellIdentifier forIndexPath:indexPath];
// Load custom image
NSString *imageName = [listeImages objectAtIndex:indexPath.row];
if (imageName)
{
UIImage *image = [UIImage imageNamed:imageName];
if (image)
{
cell.customImageView.image = image;
}
else
{
// Set an empty state here
cell.customImageView.image = [UIImage imageNamed:#"errorImage.png"];
}
}
return cell;
}
When I load the images to show to the UICollectionView I load all the images from the array like this
- (void)viewDidLoad
{
allImagesArray = [[NSMutableArray alloc] init];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *location=#"Others";
NSString *fPath = [documentsDirectory stringByAppendingPathComponent:location];
NSArray *directoryContent = [[NSFileManager defaultManager] directoryContentsAtPath: fPath];
collectionOthers.delegate =self;
collectionOthers.dataSource=self;
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];
NSLog(#"array:%#",[allImagesArray description]);
image = nil;
}
finalFilePath=nil;
data=nil;
}
paths= nil;
documentsDirectory= nil;
location= nil;
fPath= nil;
directoryContent = nil;
}
This is the biggest issue in my app since it uses so many memory. It is because number and size of the images, this could just take up memory. I would only want to load images when they are needed, and discard them when they are no longer needed.However I do not know where and how to change my code so that it will be that way. I am doing this for three month or so and I really need help.
Update
This is my code for the specific part
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *reuseID = #"ReuseID";
OthersCell *mycell = (OthersCell *) [collectionView dequeueReusableCellWithReuseIdentifier:reuseID forIndexPath:indexPath];
UIImageView *imageInCell = (UIImageView*)[mycell viewWithTag:1];
imageInCell.image = [allImagesArray objectAtIndex:indexPath.row];
NSLog(#"a");
return mycell;
}
Clearly, you should load the images just-in-time. One should never hold an array of images (because they take up a lot of memory), but rather just hold an array of filenames. So I'm suggesting you retire allImagesArray and instead define a NSMutableArray called filenames. You could then create the UIImage objects on the fly:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
OthersCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
UIImageView *imageInCell = (UIImageView*)[cell viewWithTag:1];
imageInCell.image = [UIImage imageWithContentsOfFile:filenames[indexPath.item]];
return cell;
}
This, assumes, of course, that you populated this NSMutableArray of filenames in viewDidLoad:
- (void)viewDidLoad
{
filenames = [[NSMutableArray alloc] init];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *location=#"Others";
NSString *fPath = [documentsDirectory stringByAppendingPathComponent:location];
NSArray *directoryContent = [[NSFileManager defaultManager] directoryContentsAtPath: fPath];
collectionOthers.delegate =self;
collectionOthers.dataSource=self;
for(NSString *str in directoryContent)
{
NSString *finalFilePath = [fPath stringByAppendingPathComponent:str];
[filenames addObject:fileFilePath];
}
}
This has a problem, though, because imageWithContentsOfFile (as well as loading it into a NSData first and then doing imageWithData) is a bit slow if the images aren't tiny. On slower devices, this can result in a slight stuttering of a quick scroll of a collection view. So, a better approach would be to (a) load the images asynchronously; (b) use a NSCache to optimize performance for when you scroll backwards.
So, first, define a cache:
#property (nonatomic, strong) NSCache *imageCache;
And, instantiate this in viewDidLoad:
self.imageCache = [[NSCache alloc] init];
self.imageCache.name = #"com.company.app.imageCache";
And then, cellForItemAtIndexPath can (a) set the image from the cache; and (b) if not found, retrieve the image asynchronously updating cache and cell appropriately, e.g.:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
OthersCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
UIImageView *imageInCell = (UIImageView*)[cell viewWithTag:1];
NSString *cacheKey = filenames[indexPath.item];
imageInCell.image = [self.imageCache objectForKey:cacheKey];
if (imageInCell.image == nil) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage *image = [UIImage imageWithContentsOfFile:filenames[indexPath.item]];
if (image) {
[self.imageCache setObject:image forKey:cacheKey];
dispatch_async(dispatch_get_main_queue(), ^{
OthersCell *updateCell = (id)[collectionView cellForItemAtIndexPath:indexPath];
UIImageView *imageInCell = (UIImageView*)[updateCell viewWithTag:1];
imageInCell.image = image;
});
}
});
}
return cell;
}
And, obviously, make sure you purge the cache if you receive memory warnings (in iOS 7, the cache doesn't always automatically purge itself under pressure like it used to do):
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
[self.imageCache removeAllObjects];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath
This is the method in which you should be loading the images.
In viewDidLoad, I'd build the array of NSString file paths to each image, then I'd use the collectionView:cellForItemAtIndexPath: method to load the image from the specific file path for this particular cell.
In viewDidLoad You could just load a list of available images. So remove the for loop: for(NSString *str in directoryContent) { ... } loop there (EDIT: or make it a simple for loop, just to populate an array with filenames for the files having data).
When you update a specific collectionviewcell in collectionView:cellForItemAtIndexPath:, just load the image (only 1). The cell will now hold the image data instead of your view controller. So when the cell is released, so is the image data.
This question already has an answer here:
Don't have the pictures from directory on CollectionView
(1 answer)
Closed 9 years ago.
I am showing the Pictures in all of the Directories however It does not display the pictures. I am putting NSLog in the code so that I can find out which code is working and I only get "j" in the log. I do not see the "a" in the log. What do you think is wrong?
- (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;
for(NSString *component in locations)
{
fPath = [fPath stringByAppendingPathComponent:component];
}
NSArray *directoryContent = [[NSFileManager defaultManager] directoryContentsAtPath: fPath];
collectionTrash.delegate =self;
collectionTrash.dataSource=self;
for(NSString *str in directoryContent){
NSLog(#"i");
NSString *finalFilePath = [fPath stringByAppendingPathComponent:str];
NSData *data = [NSData dataWithContentsOfFile:finalFilePath];
if(data)
{
UIImage *image = [UIImage imageWithData:data];
[allImagesArray addObject:image];
NSLog(#"array:%#",[allImagesArray description]);
}}
for(NSString *folder in locations) {
// get the folder contents
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;
}
Feel free to as for more code.
If you look at the exception, it tells you very precisely what's wrong:
You are trying to calling a 'length' method on an array, which simply does not exist. You want to use count here instead. It's not in the code you posted, though - so just do a search for length and you'll probably find it rather easily if the project isn't huge.
NSString *fPath = [documentsDirectory stringByAppendingPathComponent:locations]; gives you a warning, because locations is an array. Think about it - just doesn't make sense: which of its elements do you want to add to the path?
As I think about it, both errors probably relate to each other: You simply ignored the compile time error - or warning - for the fPath, and now the stringByAppendingPathComponent: method calls length on its parameter, which is a method of the expected NSString.
Bottom line: Do not ignore compiler warnings! If you fix those, you probably reduce crashes, too.
I would want to show all the pictures in my directory however I am creating Folders in the Directory so that I can sort the pictures. I want to show all of the pictures in several folders. I am using the code
- (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];
NSString *location=#"Bottoms"#"Top"#"Right"#"Left"#"Down"#"Up";
NSString *fPath = [documentsDirectory stringByAppendingPathComponent:location];
NSArray *directoryContent = [[NSFileManager defaultManager] directoryContentsAtPath: fPath];
collectionTrash.delegate =self;
collectionTrash.dataSource=self;
for(NSString *str in directoryContent){
NSLog(#"i");
NSString *finalFilePath = [fPath stringByAppendingPathComponent:str];
NSData *data = [NSData dataWithContentsOfFile:finalFilePath];
if(data)
{
UIImage *image = [UIImage imageWithData:data];
[allImagesArray addObject:image];
NSLog(#"array:%#",[allImagesArray description]);
}}}
- (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;
}
If you see my code you can notice that I have put NSLOG i and j. The j comes up but the i does not.... Is my way wrong showing all the pictures that are in several folders? I do not have any error.
If you have multiple folders then you need to iterate over the folders and then the folder contents to process all of it.
While this line:
NSString *location=#"Bottoms"#"Top"#"Right"#"Left"#"Down"#"Up";
Is technically legal, I guess you're thinking it will do some array / iteration thing for you. It won't. It just concatenates all of the strings together. You probably want something more like:
NSArray *locations = #[ #"Bottoms", #"Top", #"Right", #"Left", #"Down", #"Up" ];
Then you can run a loop over the folders and then the contents:
for(NSString *folder in locations) {
// get the folder contents
for(NSString *file in directoryContent) {
// load the image
}
}
I have the following code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//P1
UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell Identifier"] autorelease];
cell.textLabel.text = [photoNames objectAtIndex:indexPath.row];
//Check if object for key exists, load from cache, otherwise, load
id cachedObject = [_cache objectForKey:[photoURLs objectAtIndex:indexPath.row]];
if (cachedObject == nil) {
//IF OBJECT IS NIL, SET IT TO PLACEHOLDERS
cell.imageView.image = cachedObject;
[self setImage:[UIImage imageNamed:#"loading.png"] forKey:[photoURLs objectAtIndex:indexPath.row]];
[cell setNeedsLayout];
} else {
//fetch imageData
dispatch_async(kfetchQueue, ^{
//P1
NSData *imageData = [NSData dataWithContentsOfURL:[photoURLs objectAtIndex:indexPath.row]];
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = [UIImage imageWithData:imageData];
[self setImage:cell.imageView.image forKey:cell.textLabel.text];
[cell setNeedsLayout];
});
});
}
return cell;
}
Other than this, the viewDidLoad method fetches from the web, the json result from flickr, to populate a photoNames and photoURLs. Im trying to cache already downloaded images into a local NSDictionary. The problem is that the images arent loaded. Not even the loading.png placeholder image.
You want to save it in the app's Documents directory:
NSData *imageData = UIImagePNGRepresentation(newImage);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imagePath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png",#"cached"]];
NSLog((#"pre writing to file"));
if (![imageData writeToFile:imagePath atomically:NO])
{
NSLog((#"Failed to cache image data to disk"));
}
else
{
NSLog((#"the cachedImagedPath is %#",imagePath));
}
Then just save the path in your NSMutableDictionary with:
[yourMutableDictionary setObject:theIMagePath forKey:#"CachedImagePath"];
Then retrieve it with something like:
NSString *theImagePath = [yourMutableDictionary objectForKey:#"cachedImagePath"];
UIImage *customImage = [UIImage imageWithContentsOfFile:theImagePath];
I recommend saving the dictionary inside NSUserDefaults.