Getting url from Database and putting as an image for UITableView - ios

All,
I need to assign a picture to a UITableView. Each row has a different picture. The data for each row comes from a database and a row on that database has an ID, the ID in another database is linked and that has a URL in that table for the image.
So within cellforRowAtIndexPath we have :
NSDictionary *postValues = #{#"myParam": apt[#"barID"]};
// Do any additional setup after loading the view, typically from a nib.
self.client = [MSClient clientWithApplicationURLString:#"https://outnight-mobile.azure-mobile.net/" applicationKey:#"okYeRGfBagYrsbkaqWIRObeDtktjkF10"];
[self.client invokeAPI:#"photos"
body:postValues
HTTPMethod:#"POST"
parameters:nil
headers:nil
completion:^(id result, NSHTTPURLResponse *response, NSError *error) {
if (error) {
NSLog(#"Error %#", error );
} else
{
NSString *string = [NSString stringWithFormat:#"%#", [result objectForKey:#"rows"]];
NSString *stringWithoutbracketsend = [string stringByReplacingOccurrencesOfString:#")" withString:#""];
NSString *stringWithoutbracketsfront = [stringWithoutbracketsend stringByReplacingOccurrencesOfString:#"(" withString:#""];
NSString *completion = [stringWithoutbracketsfront stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *newStr = [completion substringFromIndex:1];
NSString *finalstring = [newStr substringToIndex:newStr.length-(newStr.length>0)];
NSLog(#"%#", finalstring);
[cell.imageView setImageWithURL:[NSURL URLWithString:finalstring] placeholderImage:[UIImage imageNamed:#"greybox40.png"]];
}
}];
That brings in the url from the table, which was JSON and I removed all the tags to get a string thats just http://blag.com/bah.jpg' This is the easy bit.
I am using SBWebImage for putting the image in the uitableview async which is fine too. What is the best way of putting the images on each row from the url. is it best with a SWITCH statement ? Is it best with an array of URL's and then displaying them. Is it best to move the database connectivity from cellforIndexRowPath? Can anyone advice please ?

first of all create a custom view cell for the uitableview. And then add subviews like images, labels to the custom cell.Get the data from the database to an array of images, arrays of ID'sIn the tableview delegate methods at cellforrowatindex use the code.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{ static NSString *CellIdentifier = #"Cell";
if(tableView == myTableView){
FirstViewCustomCell *cell = (FirstViewCustomCell *)[myTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
[[NSBundle mainBundle] loadNibNamed:#"FirstViewCustomCell" owner:self
options:nil];
cell = customCell;
customCell = nil;
}
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
//Get the data from the database.
cell.customimage.image = [imagesarr objectatIndex:indexpath.row];
cell.textlabel.text = [arrayofID objectatIndex:indexpath.row];
}

Parse the data seperately..in an method and then
Store images in an array..As you want top three images..
If you are saving the urls of image in an object and then array..Use below code
for(int i=0;i<3;i++)
{
ImagesObject *Obj=[imagesArray objectAtIndex:i];
[cell.userProfilePicImage setImageWithURL:[NSURL URLWithString:Obj.imageURLString]
placeholderImage:[UIImage imageNamed:#"greybox40.png"]
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType)
{
if (!error && image)
{
}
}];
}
(or) if you are not saving in an object then use below code.
for(int i=0;i<3;i++)
{
NSString *imageURLString=[imagesArray objectAtIndex:i];
[cell.userProfilePicImage setImageWithURL:[NSURL URLWithString:imageURLString]
placeholderImage:[UIImage imageNamed:#"greybox40.png"]
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType)
{
if (!error && image)
{
}
}];
}
Hope it helps you...

Related

Why Image is not Shown in cellforRowAtIndexPath in objective C

I am new in iOS and I am facing problem regarding to show image in the Image View from Web Service.I am using code like this
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *STI=#"STI";
NewsTableViewCell *cell = (NewsTableViewCell *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:STI];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"NewsTableViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.accessoryType=UITableViewCellAccessoryNone;
}
NSString *strImgURLAsString = [NewsImageArray objectAtIndex:indexPath.row];
[strImgURLAsString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *imgURL = [NSURL URLWithString:strImgURLAsString];
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:imgURL] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!connectionError) {
img = [[UIImage alloc] initWithData:data];
if (img==nil) {
// img=[UIImage imageNamed:#"userimage.png"];
}
cell.newsimage.image=img;
// pass the img to your imageview
}else{
NSLog(#"%#",connectionError);
}
}];
cell.Headlbl.text=[NSString stringWithFormat:#"%#",[headarray objectAtIndex:indexPath.row]];
NSString *aux = [shortnamearray objectAtIndex:indexPath.row];
NSString * htmlString = #"<html><body>";
NSString *htmlString2=#"</body></html>";
NSString * NewString=[NSString stringWithFormat:#"%#%#%#",htmlString,aux,htmlString2];
NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[NewString dataUsingEncoding:NSUnicodeStringEncoding] options:#{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
cell.bodylbl.attributedText=attrStr;
cell.bodylbl.textAlignment=NSTextAlignmentCenter;
cell.bodylbl.textColor=[UIColor whiteColor];
[cell.bodylbl setFont:[UIFont fontWithName:#"Arial" size:16]];
cell.backgroundColor = cell.contentView.backgroundColor;
// cell.bodylbl.text=[NSString stringWithFormat:#"%#",[shortnamearray objectAtIndex:indexPath.row]];
// cell.randrid.text=[NSString stringWithFormat:#"%#",[idarray objectAtIndex:indexPath.row]];
return cell;
}
Image Path - http://qaec.teams.in.net/UploadedFiles/Tommy Schaefer, of his role in the slaying, for which he is serving 18 year.png
http://qaec.teams.in.net/UploadedFiles/Tommy%20Schaefer,%20of%20his%20role%20in%20the%20slaying,%20for%20which%20he%20is%20serving%2018%20year.png
When Image Does not contain any gap it shows image
But when the Image contain any gap it not show image.How to solve this problem.Thanks in Advance!
You can use following method in UITableviewCell class. In your case add code in NewsTableViewCell.m When cell is created that time drowRect method is called. So in this method you need to set setClipsToBounds property of image view for which you setting the image to YES. This will solve your issue.
-(void)drawRect:(CGRect)rect
{
[super drawRect:rect];
self.profilePicImgView.layer.cornerRadius=self.profilePicImgView.frame.size.width/2;
[self.profilePicImgView setClipsToBounds:YES];
[self.profilePicImgView layoutIfNeeded];
[self.profilePicImgView setNeedsDisplay];
}
There is no need to use any other library etc. Your code is mistake on this line:
[strImgURLAsString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Have a look at this what does it do? Nothing. You should reassign the variable strImgURLAsString to this then it should work:
strImgURLAsString = [strImgURLAsString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
For better performance, you can try this library called SDWebImage.
[imageView sd_setImageWithURL:[NSURL URLWithString:#"http://qaec.teams.in.net/UploadedFiles/Tommy%20Schaefer,%20of%20his%20role%20in%20the%20slaying,%20for%20which%20he%20is%20serving%2018%20year.png"] placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
Also
You need to make sure that you have written this in your plist file
Use like this:
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:imgURL] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!connectionError) {
dispatch_async(dispatch_get_main_queue(), ^{
img = [[UIImage alloc] initWithData:data];
if (img==nil) {
// img=[UIImage imageNamed:#"userimage.png"];
}
cell.newsimage.image=img;
// pass the img to your imageview
});
}else{
NSLog(#"%#",connectionError);
}
}];
I know it's good to idea to load image url in Imageview like the way you have written for better understanding of process. But maintaining cache is also important thing to consider. For better performance, I recommend you to use a very good library called SDWebImage. It helps you out in loading images faster with it's cache mechanism. Try this out. With this library it's this much simple.
[imageView sd_setImageWithURL:[NSURL URLWithString:#"http://www.domain.com/path/to/image.jpg"]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
Here is another one.
If you are using AFNetworking in your app, use below code to do that.
AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
requestOperation.responseSerializer = [AFImageResponseSerializer serializer];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Response: %#", responseObject);
_imageView.image = responseObject;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Image error: %#", error);
}];
[requestOperation start];

asynchronous image downloading in tabelviewcell?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"cell";
TVcell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[TVcell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.titleLabel.text = [[[arrayData objectAtIndex:indexPath.row]valueForKey:#"title"]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
cell.txtlabel.text = [[[arrayData objectAtIndex:indexPath.row] valueForKey:#"description"]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
cell.tag = indexPath.row;
cell.imageView.image = nil;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^(void) {
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[enclosureUrlArray objectAtIndex:indexPath.row]]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
if (image) {
dispatch_async(dispatch_get_main_queue(), ^{
if (cell.tag == indexPath.row) {
cell.IMGLabel.image = image;
[cell setNeedsLayout];
}
});
}
});
return cell;
}
while i'm scrolling that same images are appearing on the cells,which cells im reusing.i used scroll view delegate also.im storing urls in enclosureUrlArray and i'm passing.
Put cell.IMGLabel.image = nil in your cellForRowAtIndexPath before downloading image, i.e. below cell.imageView.image = nil; this line.
Or set some place holder image (no image available kind of image to cell's image in interface builder), so if image is not downloaded then it will show this place holder image otherwise it will show downloaded image.
SDWebImage is good for this kind of case. It will cache the images so it will give better performance also. There is nothing wrong to use any good third party library.
By using SDWeb image:
#import <SDWebImage/UIImageView+WebCache.h>
...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:MyIdentifier] autorelease];
}
// Here we use the new provided sd_setImageWithURL: method to load the web image
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:#"http://www.domain.com/path/to/image.jpg"]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
cell.textLabel.text = #"My Text";
return cell;
}
You can also use NSURLSession as well,see this link
Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling
NSURL *url = [NSURL URLWithString:[enclosureUrlArray objectAtIndex:indexPath.row]];
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (data) {
UIImage *image = [UIImage imageWithData:data];
if (image) {
dispatch_async(dispatch_get_main_queue(), ^{
MyCell *updateCell = (id)[tableView cellForRowAtIndexPath:indexPath];
if (updateCell)
updateCell.IMGLabel.image = image;
});
}
}
}];
[task resume];
works perfect for me..
with the help of sdwebimage you can show the image like this:-
NSString *string2 = [[businessListArray objectAtIndex:indexPath.row ]valueForKey:#"logo"];
NSURL *url1 = [NSURL URLWithString:
[NSString stringWithFormat:
#"%#%#",
#"http://dev-demo.info.bh-in-15./upload/post/",
string2]];
UIImageView *imageView = (UIImageView *)[cell.contentView viewWithTag:301];
[imageView sd_setImageWithURL:url1
placeholderImage:[UIImage imageNamed:#"pocket.png"]
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
imageView.image = image;
}];

After reloading UITableView data, indexPathForCell returns null

I have a UITableView in a ViewController which contains a custom cell.
When the view first loads, the indexPathForCell in the following code returns the indexPath without problems:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
PostCell *postCell = (PostCell *)[tableView dequeueReusableCellWithIdentifier:#"PostCell"];
if (postCell == nil) {
NSLog(#"EmptyCell Found");
}
NSDictionary *object = [postArray objectAtIndex:indexPath.row];
NSString *imageURL = [object objectForKey:#"imageURL"];
NSIndexPath *originalIndexPath = indexPath;
NSLog(#"Original IndexPath %#", originalIndexPath);
SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadWithURL:[NSURL URLWithString:imageURL]
options:indexPath.row == 0 ? SDWebImageRefreshCached : 0
progress:^(NSInteger receivedSize, NSInteger expectedSize){}
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished){
if (image) {
// This returns correctly on first load
NSIndexPath *currentIndexPath = [imageTableView indexPathForCell:postCell];
NSLog(#"Current IndexPath %#", currentIndexPath);
}
}
];
}
After refreshing the tableView, currentIndexPath is always (null).
The following is my refresh code:
- (void)refreshMainView {
AFHTTPRequestOperation *downloadPostOperation = [[AFHTTPRequestOperation alloc] initWithRequest:serviceRequest];
[downloadPostOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//[tableView beginUpdates];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:urlData options:kNilOptions error:&error];
NSMutableArray *newPostArray = [json objectForKey:#"posts"];
// Replacing the old array with new array
postArray = newPostArray;
[self stopRefresh];
//[tableView endUpdates]
[imageTableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[self stopRefresh];
}];
If I just perform [tableView reloadData] without performing refreshMainView, there will not be any problem with getting the currentIndexPath.
There must be something I am overlooking, could someone please help me? Thank you!
Edit:
I have tried [postCell.postImageView setImageWithURL:[NSURL URLWithString:imageURL] placeholderImage:nil]; instead and the refreshing works, so I am suspecting that something is wrong with me getting the indexPath in the completed block, can anyone help out please? I need the completed block as I am doing some image processing.
Hi I have finally fixed it.
For people who are needing answers, just add
dispatch_async(dispatch_get_main_queue(), ^{
});
around the portion that is retrieving the indexPathForCell.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
PostCell *postCell = (PostCell *)[tableView dequeueReusableCellWithIdentifier:#"PostCell"];
if (cell == nil)
{
nib = [[NSBundle mainBundle] loadNibNamed:#"PostCell" owner:self options:nil];
}
NSIndexPath *originalIndexPath = indexPath;
NSLog(#"Original IndexPath %#", originalIndexPath);
SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadWithURL:[NSURL URLWithString:imageURL]
options:indexPath.row == 0 ? SDWebImageRefreshCached : 0
progress:^(NSInteger receivedSize, NSInteger expectedSize){}
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished){
if (image) {
// This returns correctly on first load
NSIndexPath *currentIndexPath = [imageTableView indexPathForCell:postCell];
NSLog(#"Current IndexPath %#", currentIndexPath);
}
}
];
use this it may help you

how can i display images in uitableviewcells using Asyncronous concept in ios

I have to show some post blogs into a UITableView. When I have retreived all web service data.
This is my sample code.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
NSError *err;
NSString *strResponse=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"response is %#",strResponse);
dit=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&err];
NSArray *arrResults = [dit valueForKey:#"classifieds_mst"];
listOfObjects = [NSMutableArray array];
for(dictRes in arrResults)
{
Attributes *at = [[Attributes alloc]init];
at.classimage=[dictRes valueForKey:#"image_name"];
[listOfObjects addObject:at];
}
[tableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier=#"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"identifier"];
}
classifiedimage=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 300, 80)];
[cell.contentView addSubview:classifiedimage];
Attributes *att = [listOfObjects objectAtIndex:indexPath.row];
NSString *str;
str=att.classimage;
classifiedimage.image = [UIImage imageNamed:str];
return cell;
}
My requirement is i want to display images in uitableviewcells using json parser.I wrote the above code.But the images are not displayed in uitableviewcells.I want to use to display images in uitableviewcells using Asyncronous concept.Please give me any idea.I am new to the programming.Thanks in advance.
This is my json data.
{"classifieds_mst":[{"classified_id":83,image_name":"1389006378_butterfly.jpeg"},
{"classified_id":82,"image_name":"ttt.jpj"},{"classified_id":83,”image_name":"ttttt.jpj”}
imageNamed is used to load image from local bundle (in app).
imageWithData:dataWithURL is used to load images from url's.
You have to append domain name in your image name: (image_name":"1389006378_butterfly.jpeg), so that you can get URL of the image which is stored on server, now you can use below code:
[cell.yourImageView setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:yourImageNameHere]]]];
By referring to your JSON data, it just contain the image_name only. So first of all, you need to build the actual image url. (copy paste that actual url in browser to make sure image is available in server).
Once you have the image url, then you can use AsyncImageView instead of UIImageView in your cell. It will handle the asynchronous thing for you as you just need to set the image url only. Thats the way to go.
One more suggestion is to recheck you cellForRowAtIndexPath, as the code always creating imageView's and adding to cell each time the cell is created. That's not required when you are reusing a cell. You just need to create the image view once when cell is allocated and just assign a tag to imageview and then get the imageview based on this tag and then use it. Just for your reference, I'm posting a sample code:
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"identifier"];
AsyncImageView *imgView= [[[AsyncImageView alloc]init]autorelease];
imgView.tag = 1000;
imgView.contentMode = UIViewContentModeScaleAspectFill;
[cell.contentView addSubview:imgView];
}
AsyncImageView *imgView= (AsyncImageView*)[cell.contentView viewWithTag:1000];
contactImgView.frame = CGRectMake(0, 0, 300, 80);
//imgUrl is the actual url of image that is available in datasource
[contactImgView setImageURL:imgUrl];
Hope it is clear.
if you are using the AFNetworking then use it to download your image like
NSArray *keys = #[#"UserID", ];
NSArray *objects = #[#(userId)];
NSDictionary *parameter = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:
[NSURL URLWithString:BaseURLString]];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:#"UserService.svc/GetUserInfo"
parameters:parameter];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError* error = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
[SVProgressHUD dismiss];
});
}];
[operation start];
and for image use this
[cell.userImage setImageWithURLRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:userBasicInfo.imageUrl]]
placeholderImage:[UIImage imageNamed:#"facebook-no-user.png"]
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image){
weakCell.userImage.image = image;
[weakCell setNeedsLayout];
} completion:^(BOOL success, NSError *error) {
NSLog(#"%#",[error localizedDescription]);
}];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error){
}];
You Create a subclass of UITableViewCell (can call it blogTableViewCell) for your cell and use that in the table.
Initialize blogTableViewCell with the JSON data (you could have an NSDictionary store the JSON info)
In blogTableViewCell create a function that loads image data on another thread (so the main thread can continue its course) and once the image is loaded, update the uiimageview on the cell to display it (This should be done on the main thread as it is a UI update)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// Configure the cell...
//cell.textLabel.text = [[resultArray objectAtIndex:indexPath.row] valueForKey:#"name"];
cell.detailTextLabel.text = [[resultArray objectAtIndex:indexPath.row] valueForKey:#"designation"];
cell.imageView.image=[UIImage imageNamed:[[resultArray objectAtIndex:indexPath.row] valueForKey:#"image"]] ;
//[cell.imageView setImageWithURL:[NSURL URLWithString:[[resultArray objectAtIndex:indexPath.row] objectForKey:#"image"]]];
// NSURL *url = [NSURL URLWithString:[resultArray objectAtIndex:indexPath .row]];
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[resultArray objectAtIndex:indexPath.row] valueForKey:#"image"] ]];
cell.imageView.image = [UIImage imageWithData:imageData];
return cell;
}

SDWebImage With Custom UITableView Cell Image

I am trying to use SDWebImage library with a custom UITableViewCell. Below is the method that is downloading the images from the web service:
- (void) downloadThumbnails:(NSURL *)finalUrl
{
SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadWithURL:finalUrl
options:0
progress:nil
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished)
{
if (image)
{
// do something with image
// THERE I HAVE TO ASSIGN the property "thumbnail" with the "image"
// So it can be used by the tableview controller class
}
}];
}
The above code is in a separate file named RSSItem. While my UITableViewController class has the following cellForRowAtIndexPath method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ItemsCell";
ItemsViewCell *cell = (ItemsViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
RSSItem *item = [[channel items] objectAtIndex:[indexPath row]];
cell.titleLabel.text = [item title];
cell.creatorLabel.text = [item creator];
cell.pubTimeLabel.text = [item pubTime];
cell.thumbContainer.image = [item thumbnail];
return cell;
}
Can somebody point out how can i configure the if (image) inside downloadThumbnails method? I just need to assign "image" to the property "thumbnail", how can i do that?
Looks like you have already used the right method to download images asynchronously using SDWebImage. All you need to do is to set the thumbnail property to the "image". Here is how you can do it:
- (void) downloadThumbnails:(NSURL *)finalUrl
{
SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadWithURL:finalUrl
options:0
progress:nil
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished)
{
if (image)
{
[self setThumbnail:image];
}
}];
}

Resources