How to set image path coming from server in uitableviewcell - ios

I am making an app in which i am getting data from server and in data image path is also coming but when i am setting image to my tableview cell app will become too much heavy may b i am not setting image properly below is my sample code thanx in advance :)
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *tableviewidentifier = #"cell";
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){
// [[cell textLabel] setText:#"Load more records"];
}
UILabel *valuedate = (UILabel *)[cell viewWithTag:21];
UILabel *msg = (UILabel *)[cell viewWithTag:22];
UILabel *date = (UILabel *)[cell viewWithTag:23];
UILabel *time = (UILabel *)[cell viewWithTag:24];
valuedate.text=[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:#"offerTitle"];
msg.text=#"How are you?";
NSString *img=[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:#"offerPhoto"];// here i am getting image path
UIImage *img1 = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:img]]];
cell.imageView.image=img1;// here i am setting image due to which app is so heavy and stuck
return cell;
}

Dont use imageWithData: for setting images. It is synchronous and will make your app run slow.
Instead of that Use SDWebImage
You just need to do following things:
Dump SDWebImage folder into your project.
Import UIImageView+WebCache.h.
Set the image using: sd_setImageWithURL:
OR
by GCD (Grand Central Dispatch) and sending asynchronous requests. Code copied from HERE.
First implement following method.
- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if ( !error )
{
UIImage *image = [[UIImage alloc] initWithData:data];
completionBlock(YES,image);
} else{
completionBlock(NO,nil);
}
}];
}
and then in your cellForRowAtIndexPath
[self downloadImageWithURL:your_url completionBlock:^(BOOL succeeded, UIImage *image) {
if (succeeded) {
// change the image in the cell
cell.imageView.image = image;
}
}];

try this below code, hope this helps u .
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
__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)
{
// [[cell textLabel] setText:#"Load more records"];
}
UILabel *valuedate = (UILabel *)[cell viewWithTag:21];
UILabel *msg = (UILabel *)[cell viewWithTag:22];
UILabel *date = (UILabel *)[cell viewWithTag:23];
UILabel *time = (UILabel *)[cell viewWithTag:24];
valuedate.text=[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:#"offerTitle"];
msg.text=#"How are you?";
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
cell.imageView.image = image;
cell.textLabel.text = #""; //add this update will reflect the changes
});
});
return cell;
}
EDIT
in order to reuse the downloaded image u can either save them on disk or just for save them some where for example in dictionary for temporary using
in below code i took one example dictionary, and strong the download images with row as key
#interface ViewController ()
{
NSMutableDictionary *imagesDictionary; //lets declare a mutable dictionary to hold images
}
in this method just initialise it
- (void)viewDidLoad {
[super viewDidLoad];
// rest of your code
//...........
//
imagesDictionary = [[NSMutableDictionary alloc]init]; //initilise
}
in index this method just add the downloaded images to dictionary for corresponding row as key
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
__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)
{
// [[cell textLabel] setText:#"Load more records"];
}
__block NSString *row = [NSString stringWithFormat:#"%d",indexPath.row]; //add this
UILabel *valuedate = (UILabel *)[cell viewWithTag:21];
UILabel *msg = (UILabel *)[cell viewWithTag:22];
UILabel *date = (UILabel *)[cell viewWithTag:23];
UILabel *time = (UILabel *)[cell viewWithTag:24];
// 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]; //sorry, while editing to your code i forgot to add this
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");
}
return cell;
}

First of all you are calling dataWithContentsOfURL: function which will make the app non responsive because you are calling it on main thread. To make it responsive you need to create a custom cell YourCell and declare a method in YourCell.h
#interface YourCell : UITableViewCell
{
UIImage *_cImage;
}
- (void)downloadImageFromURL:(NSURL *)imageUrl;
#end
Now in YourCell.m you need to do like this:
- (void)downloadImageFromURL:(NSURL *)imageUrl
{
if (_cImage != nil)
{
self.imageView.image = _cImage;
}
else
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
_cImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageUrl]];
dispatch_sync(dispatch_get_main_queue(), ^{
self.imageView.image = _cImage;
});
});
}
}
Now from cellForRowAtIndexPath: you just need to call downloadImageFromURL: function of YourCell and pass the imageUrl to it and its the cell responsibility to download and show the image.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier= #"YourCell";
YourCell *cell = (YourCell *)[self.activitiesTableView_ dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[NSBundle mainBundle] loadNibNamed:#"YourCell" owner:self options:nil] objectAtIndex:0];
}
// Set your UILabels as before.....
NSString *imagePath=[[self.inboxmessagesarray objectAtIndex:indexPath.row] objectForKey:#"offerPhoto"];
[cell downloadImageFromURL:[NSURL URLWithString:imagePath]];
return cell;
}
Let me know if you have any questions.

UIImageView *img1 = (UIImageView *)[cell viewWithTag:104];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
img1.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:img]]];
});
});
Send async requests for images. Doing this would not block your UI until the image gets loaded.

Related

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

Showing/Hiding button in custom cell on demand not working

I'm trying to show a button on certain cells in my tableview depending on type of image showing in that cell
soo i have two NSMutableArray's one holding the thumbnail image URL's and the other NSMutableArray holding the type of the url if it was image or video
the problem is the button doesn't show on all the video type cells
here is my code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"TVCustomCell";
TVCustom *cell = (TVCustom *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"TVCustom" owner:self options:nil];
for (id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[TVCustom class]]) {
cell = (TVCustom *) currentObject;
break;
}
}
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *imgURL = [arrayImagesURL objectAtIndex:indexPath.row];
NSURL *imageURL = [NSURL URLWithString:imgURL];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *image = [UIImage imageWithData:imageData];
cell.thumbImg.image = image;
});
});
NSString *MediaType = [NSString stringWithFormat:#"%#", [arrayType objectAtIndex:indexPath.row]];
if ([MediaType isEqualToString:#"video"]) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(120, 319, 50, 30);
[button setTitle:#"Play" forState:UIControlStateNormal];
button.tag = indexPath.row;
[button addTarget:self action:#selector(PlayBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor= [UIColor clearColor];
[cell.contentView addSubview:button];
}
return cell;
}
i don't know what i'm doing wrong, any idea ?
I see different problems here.
First
Your code creates new buttons every time the user scrolls in the tableView. This is because you use dequeueReusableCellWithIdentifier which is great and returns existing cells instead of creating new ones.
But then you add a new button on cells which already exist (and may or may not have a button)
[cell.contentView addSubview:button];
I suggest you add the button in your TVCustom class:
In the TVCustom.h
#property (strong, nonatomic) UIButton *viedoButton;
In TVCustom.m
- (UIButton *)videoButton
{
if (!_videoButton) {
_videoButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
_videoButton.frame = CGRectMake(120, 319, 50, 30);
[_videoButton setTitle:#"Play" forState:UIControlStateNormal];
[_videoButton addTarget:self action:#selector(PlayBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
_videoButton.backgroundColor= [UIColor clearColor];
[self.contentView _videoButton];
}
return _videoButton;
}
Then in - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath you only do :
if ([MediaType isEqualToString:#"video"]) {
cell.videoButton.hidden = NO;
} else {
cell.videoButton.hidden = YES;
}
This way every cell will have only one button and it will be visible only when you need it but not re-allocated every time. But PlayBtnClicked will have to be in your TVCustom class and call your viewController through a delegate.
Second
You should not handle the loading of your image in the cellForRowAtIndexPath method. Encapsulate it your TVCustom class:
In TVCustom.h
#property (strong, nonatomic) NSString *imgURL;
In TVCustom.m
- (void)setImgURL:(NSString *)imgURL
{
_imgURL = imgURL;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL *imageURL = [NSURL URLWithString:imgURL];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *image = [UIImage imageWithData:imageData];
self.thumbImg.image = image;
});
});
}
Then in cellForRowAtIndexPath it will look like :
cell.imgURL = [arrayImagesURL objectAtIndex:indexPath.row];
Third
I do not know if you have any particular reason for this:
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"TVCustom" owner:self options:nil];
for (id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[TVCustom class]]) {
cell = (TVCustom *) currentObject;
break;
}
}
}
But a good way to do this is in your viewController's viewDidLoad (or other method):
NSString *identifier = #"TVCustomCell";
NSString *nibName = #"TVCustom";
UINib *cellNib = [UINib nibWithName:nibName];
[self.tableView registerNib:cellNib forCellReuseIdentifier:identifier];
Your final code should look like :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"TVCustomCell";
TVCustom *cell = (TVCustom *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.imgURL = [arrayImagesURL objectAtIndex:indexPath.row];
if ([MediaType isEqualToString:#"video"]) {
cell.videoButton.hidden = NO;
} else {
cell.videoButton.hidden = YES;
}
return cell;
}

reloading UItableViewCell after thumbnail image downloads

I have an app in which within the tableViewCell an image is downloaded and than set as a thumbnail. My problem is that the only way I can see the thumbnail image refresh is if I click on another tab, and than come back to the tab that the tableViewCell is being held. Below is the code for setting the thumbnail.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
PFObject *message = [self.messages objectAtIndex:indexPath.row];
cell.textLabel.text = [message objectForKey:#"username"];
cell.imageView.image = [UIImage imageNamed:#"Treehouse.png"];
PFFile *thumbnail = nil;
if (thumbnailArray.count > 0){
thumbnail = [[thumbnailArray objectAtIndex:indexPath.row] objectForKey:#"imageFile"];
dispatch_async(backgroundQueue, ^{
NSURL *thumbnailURL = [[NSURL alloc]initWithString:thumbnail.url];
NSData *thumbnailData = [NSData dataWithContentsOfURL:thumbnailURL];
[[cell imageView]setImage:[UIImage imageWithData:thumbnailData]];
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
});
}
return cell;
}
The problem is.,
The cell is loaded.
The image download is fired.
Once image is downloaded, the cell is reloaded.
The image is downloaded again.
There is no caching of the image or logic to load the image
Declare a NSMutableDictionary #property (strong) NSMutableDictionary *imagesDictionary; and instantiate it self.imagesDictionary = [NSMutableDictionary dictionary];
In cell for Row at index path, check for the presence of cache before downloading it.
PFFile *thumbnail = nil;
if (thumbnailArray.count > 0)
{
//If image is present in cache load from cache
UIImage *image = [self.imagesDictionary objectForKey:indexPath];
if (image)
{
[cell.imageView setImage:image];
}
else
{
//If Image is not present fire a download
thumbnail = [[thumbnailArray objectAtIndex:indexPath.row] objectForKey:#"imageFile"];
dispatch_async(backgroundQueue, ^{
NSURL *thumbnailURL = [[NSURL alloc]initWithString:thumbnail.url];
NSData *thumbnailData = [NSData dataWithContentsOfURL:thumbnailURL];
//Cahce it to your image dictionary
[self.imagesDictionary setObject:[UIImage imageWithData:thumbnailData] forKey:indexPath];
//Reload the dictionary
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
});
}
I recommend you use AFNetworkings category UIImage+AFNetworking which allows you to just do [imageView setImageWithURL:(NSURL)] which manages everything in the background. You don't have to worry about loading the image, caching the image or anything like that. It will cache it for you.
https://github.com/AFNetworking/AFNetworking
The following code helped solve my problem
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
PFObject *message = [self.messages objectAtIndex:indexPath.row];
cell.textLabel.text = [message objectForKey:#"username"];
cell.imageView.image = [UIImage imageNamed:#"Treehouse.png"];
PFFile *thumbnail = nil;
if (thumbnailArray.count > 0){
thumbnail = [[thumbnailArray objectAtIndex:indexPath.row] objectForKey:#"imageFile"];
dispatch_async(backgroundQueue, ^{
NSURL *thumbnailURL = [[NSURL alloc]initWithString:thumbnail.url];
NSData *thumbnailData = [NSData dataWithContentsOfURL:thumbnailURL];
dispatch_sync(dispatch_get_main_queue(), ^{
[[cell imageView]setImage:[UIImage imageWithData:thumbnailData]];
[tableView reloadInputViews];
});
});
}
return cell;
}
The problem was that reloading the TableView was being called on a separate thread. Once I moved the setting of the image onto the main thread and calling reloadInputViews from there, my problem was fixed.

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