UICollectionView doesn't display any image - ios

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

Related

Failed to load image in a UICollectionView

I need to show flickr public images in a UICollectionView. I have done all the things, but images don't load in the UICollectionView. I am new to objective-c. Please help.
authorIds = [[NSMutableArray alloc] init];
dateTaken = [[NSMutableArray alloc] init];
smallImageUrlArray = [[NSMutableArray alloc] init];
largeImageUrlArray = [[NSMutableArray alloc] init];
smallImageArray = [[NSMutableArray alloc] init];
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
layout.minimumLineSpacing = 10;
layout.minimumInteritemSpacing = 10;
layout.sectionInset = UIEdgeInsetsMake(110, 20, 20, 20);
_collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
[_collectionView setDataSource:self];
[_collectionView setDelegate:self];
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:#"cellIdentifier"];
[_collectionView setBackgroundColor:[UIColor blackColor]];
[self.view addSubview:_collectionView];
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return totalImageNo;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
UIImageView *cellImageView = (UIImageView *)[cell viewWithTag:100];
cellImageView.image = [UIImage imageNamed:[smallImageUrlArray objectAtIndex:indexPath.row]];
//[self.view addSubview:cellImageView];
[cell.backgroundView addSubview:cellImageView];
// NSLog(#"%#",[smallImageUrlArray objectAtIndex:indexPath.row]); //Here can show Img's values correctly
cell.backgroundColor=[UIColor darkGrayColor];
return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(160, 160);
}
In below I am fetching Flickr images and storing in array. then want to load the smallImageArray in the UICollection view. but nothing shows up.
-(void)fetchFlickrPublicImages
{
NSString *urlString = [NSString stringWithFormat:#"http://api.flickr.com/services/feeds/photos_public.gne?format=json&tags=data"];
NSURL *url = [NSURL URLWithString:urlString];
NSData *badJSON = [NSData dataWithContentsOfURL:url];
NSString *dataAsString = [NSString stringWithUTF8String:[badJSON bytes]];
NSString *correctedJSONString = [NSString stringWithString:[dataAsString substringWithRange:NSMakeRange (15, dataAsString.length-15-1)]];
correctedJSONString = [correctedJSONString stringByReplacingOccurrencesOfString:#"\\'" withString:#"'"];
NSData *correctedData = [correctedJSONString dataUsingEncoding:NSUTF8StringEncoding];
NSError* error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:correctedData options:kNilOptions error:&error];
NSArray *images = [json objectForKey:#"items"];
for (NSDictionary *image in images)
{
NSString *authorId = [image objectForKey:#"author_id"];
[authorIds addObject:(authorId.length > 0 ? authorId: #"Untitled")];
NSString *largeImageUrl = [NSString stringWithFormat:#"%#",[[image objectForKey:#"media"] objectForKey:#"m"]];
NSString *smallImageUrl = [largeImageUrl stringByReplacingOccurrencesOfString:#"_m" withString:#"_s"];
[smallImageUrlArray addObject:smallImageUrl];
[dateTaken addObject:[NSString stringWithFormat:#"%#",[image objectForKey:#"date_taken"]]];
[largeImageUrlArray addObject:[NSString stringWithFormat:#"%#",[[image objectForKey:#"media"] objectForKey:#"m"]]];
totalImageNo = authorIds.count;
}
for (int i=0; i< smallImageUrlArray.count; i++) {
UIImage * image = [UIImage imageWithData:[NSData dataWithContentsOfURL:
[NSURL URLWithString:[smallImageUrlArray objectAtIndex:i]]]];
[smallImageArray addObject:image];
}
NSLog(#"%#", smallImageArray);
NSLog(#"%ld", (long)totalImageNo);
// NSLog(#"authorIds: %#\n\n", authorIds);
// NSLog(#"photoURLsLareImage: %#\n\n", smallImageUrlArray);
// NSLog(#"photoURLsLareImage: %#\n\n", largeImageUrlArray);
}
You should add your UIImageView to the collection view cell's contentView, NOT backgroundView.
In your code ,
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UIImageView *cellImageView = (UIImageView *)[cell viewWithTag:100];
cellImageView.image = [UIImage imageNamed:[smallImageUrlArray objectAtIndex:indexPath.row]];
[cell.backgroundView addSubview:cellImageView];
}
you are assigning image as url . but in your method named fetchFlickrPublicImages where you are downloading images directly.
better you write code like
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UIImageView *cellImageView = (UIImageView *)[cell viewWithTag:100];
cellImageView.image =(UIImage*)[smallImageArray objectAtIndex:indexPath.row];
[cell.contentView addSubView cellImageView];
}

Uilabel is not visible in collectionview

Im using the following code to load images from url into collection view
-
(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = #"Cell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
UILabel *recipeLabel = (UILabel *)[cell viewWithTag:200];
if ([ImageArray count] >0){
for(int i = 0; i < [ImageArray count]; i++)
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^(void) {
NSData *data0 = [NSData dataWithContentsOfURL: [NSURL URLWithString:[ImageArray objectAtIndex:indexPath.row]]];
UIImage *image = [UIImage imageWithData: data0];
dispatch_sync(dispatch_get_main_queue(), ^(void) {
recipeImageView.image = image;
});
});
}
}else{
UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, cell.bounds.size.width, 40)];
title.text = #"No image record found";
title.tag = 200;
[title setHidden:true];
[cell.contentView addSubview:title];
}
[spinnerShow stopAnimating];
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
return cell;
}
If the ImageArray has got some url, if loop will be executed. Else the else loop will be executed where it will display a label saying no image record found. But the uilabel is not getting visible
Why are you using for loop in cellForItemAtIndexPath? This method is called for every item in UICollectionView. In else condition, add log or breakpoint and check if it is going there or always going in if condition. Make sure if you need to check for array count or want to check if image exists on URL?

position of image is not changing while changing position of uiimageview controller

i am making an app in which i am placing an imageview in uitableview cell but when i am chnaging my image view position on story board and then run the application but that image is not appearing according to the position of uiimage view below i am adding screen shots
and below is my tableview cell for row at indexpath code
static NSString *tableviewidentifier = #"cell";
__block tablecellTableViewCell *cell= [self.activitiesTableView_ dequeueReusableCellWithIdentifier:tableviewidentifier];
if(cell==nil)
{
cell = [[tablecellTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:tableviewidentifier];
}if(indexPath.row == [self tableView:tableView numberOfRowsInSection:indexPath.section] - 1){
}
__block NSString *row = [NSString stringWithFormat:#"%d",indexPath.row];
UILabel *valuedate = (UILabel *)[cell viewWithTag:21];
UILabel *msg = (UILabel *)[cell viewWithTag:22];
UILabel *date = (UILabel *)[cell viewWithTag:23];
UILabel *time = (UILabel *)[cell viewWithTag:24];
if([[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:#"messageRead"] intValue]==0)
{
cell.contentView.backgroundColor=[UIColor colorWithRed:(245/255.0) green:(245/255.0) blue:(245/255.0) alpha:1];
}
else
{
cell.contentView.backgroundColor=[UIColor clearColor];
}
valuedate.text=[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:#"offerTitle"];
msg.text=#"How are you?";
if(![[imagesDictionary allKeys] containsObject:row]) //if image not found download and add it to dictionary
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
NSString *img=[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:#"offerPhoto"];// here i am getting image path
NSURL *url = [NSURL URLWithString:img];
NSData * imageData = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:imageData];
dispatch_sync(dispatch_get_main_queue(), ^{ //in main thread update the image
[imagesDictionary setObject:image forKey:row];
cell.imageView.image = image;
cell.textLabel.text = #""; //add this update will reflect the changes
NSLog(#"loading and addig to dictionary");
});
});
}
else
{
cell.imageView.image = [imagesDictionary objectForKey:row];
NSLog(#"retriving from dictioary");
}
date.text=[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:#"messageDate"];
time.text=[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:#"messageTime"];
return cell;
}
I think u are setting the default image of cell not the image view which is present in custom cell
in the above code cell.imageView.image is the default image of cell. Change the name of the image view which is present in custom cell to some different name for example profileImageView then set the image something like
cell. profileImageView.image = myImage;
in the above code u are using the custom tableview cell's image view

UITableView cell won't select

I have a UITableView which contains a UIImage and a title per cell. I'm getting the image from my db which contains the path of the picture generate via the ALAssetsLibrary. Problem is whenever I include the photo in the table, I can't select the cell. Any help would be appreciated
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIndentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIndentifier];
}
Person *aPerson = [arrayOfPerson objectAtIndex:indexPath.row];
UIImage *background = [self cellBackgroundForRowAtIndexPath:indexPath];
UIImageView *cellBackgroundView = [[UIImageView alloc] initWithImage:background];
cellBackgroundView.image = background;
cell.backgroundView = cellBackgroundView;
UILabel *myLabel = (UILabel *) [cell viewWithTag:101];
myLabel.text = aPerson.title;
NSString *stPath = [NSString stringWithFormat:#"%#", aPerson.photo];
NSURL *urlNow = [NSURL URLWithString:stPath];
ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
[assetslibrary assetForURL:urlNow resultBlock:^(ALAsset *imageAsset) {
ALAssetRepresentation *r = [imageAsset defaultRepresentation];
UIImageView *myImageView = (UIImageView *)[cell viewWithTag:100];
myImageView.image = [UIImage imageWithCGImage: r.fullResolutionImage];
//[cell.contentView addSubview:myImageView];
[self.tableView reloadData];
} failureBlock:nil];
return cell;
New image view objects are configured to disregard user events by default. If you want to handle events in a custom subclass of UIImageView, you must explicitly change the value of the userInteractionEnabled property to YES after initializing the object.
UIImageView *cellBackgroundView = [[UIImageView alloc] initWithImage:background];
cellBackgroundView.userInteractionEnabled = YES;
Note:
When you are dealing with Asset Library images, Please look at my this answer that may help you for better performance.

Asynchronous images loading again and again in the Uitableview cells

Having trouble with the asynchronous images don't know why having this weird problem. I am applying the Asynchronous images load technique but the images are not freezing once loaded on scrolling they are again loading.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell=[self getCellContentView:CellIdentifier];
}
[cell setBackgroundColor:[UIColor redColor]];
NSLog(#"%i",[discussionArray count]);
NSDictionary *dict=[discussionArray objectAtIndex:indexPath.row];
UILabel *textLabel1 = (UILabel *)[cell viewWithTag:1];
UILabel *textLabel2 = (UILabel *)[cell viewWithTag:2];
UILabel *textLabel3 = (UILabel *)[cell viewWithTag:3];
UIImageView *avatarimage = (UIImageView *)[cell viewWithTag:4];
UIImageView *new_oldimage = (UIImageView *)[cell viewWithTag:5];
UIImageView *avatarimage_cover = (UIImageView *)[cell viewWithTag:6];
textLabel1.text =[dict objectForKey:#"user"];
textLabel2.text =[dict objectForKey:#"date"];
textLabel3.text =[dict objectForKey:#"text"];
NSString *photoStrn=[dict objectForKey:#"photo"];
avatarimage.image = nil;
dispatch_async(dispatch_get_global_queue(0,0), ^{
NSString *u=[NSString stringWithFormat:#"http://%#",photoStrn];
NSURL *imageURL=[NSURL URLWithString:u];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
dispatch_sync(dispatch_get_main_queue(), ^{
UIImage *dpImage = [UIImage imageWithData:imageData];
if (dpImage==nil)
{
dpImage = [UIImage imageNamed:#"profileImage.png"];
}
[UIView animateWithDuration:5.0 animations:^{
avatarimage.alpha = 1.0;
}];
avatarimage.image = dpImage;
});
});
avatarimage_cover.image = [UIImage imageNamed:#"avtrcover.png"];
NSString *new=[dict objectForKey:#"new"];
if ([new isEqualToString:#"0"])
{
new_oldimage.image = [UIImage imageNamed:#"old_message.png"];
}
else
{
new_oldimage.image = [UIImage imageNamed:#"new_message.png"];
}
textLabel3.numberOfLines = 0;
NSString *detailText = [[discussionArray objectAtIndex:indexPath.row] objectForKey:#"text"];
CGSize textSize = [detailText sizeWithFont:[UIFont boldSystemFontOfSize:13] constrainedToSize:CGSizeMake(240, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
textLabel3.frame = CGRectMake(70, 53, 240, textSize.height+detailTextoffset );
return cell;
}
You are setting avatarimage.image to nil each time the cell is configured. You call the loading code regardless what. Thus, it is not surprising you keep reloading the image.
Instead, you should maintain a mutable array of downloaded images. This could be just file URLs for the images somewhere in the documents folder. If the image exists use it, if not download it.
if (imageArray[indexPath.row]) {
// use the image to populate the image view
}
else {
// fetch async from server
}
this will solve you problem completely. click on below link:
Image on top of Cell

Resources