Fetching and displaying facebook profile picture in a UIImage - iphone

I'm trying to make a facebook friend picker displaying the friends who currently have the app installed that are also facebook friends with the current user.
Here I'm fetching the user's facebook profile picture but, I seem to have a warning where the last statement is not used. Thanks for your help.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"friendCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
PFUser *facebookID = [[PFUser alloc] init];
facebookID = [friendUsers objectAtIndex:0];
NSString *fbIdString = [[NSString alloc] init];
fbIdString = [facebookID objectForKey:#"fbId"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
NSURL *profilePictureURL = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large", fbIdString]];
NSData *picData = [NSData dataWithContentsOfURL:profilePictureURL];
UIImage *fbPic = (UIImage *)[self.view viewWithTag:1001];
[fbPic initWithData:picData];
}
// Configure the cell...
return cell;
}

You need to actually assign the result of the initWithData: call to your fbPic image.
E.g.
fbPic = [fbPic initWithData: picData];
From the apple documentation on UIImage:
- (id)initWithData:(NSData *)data
Parameters
data -
The data object containing the image data.
Return Value
An initialized UIImage object, or nil if the method could not initialize the image from the specified data.

A couple of things:
UIImage *fbPic = (UIImage *)[self.view viewWithTag:1001]; - I think you're trying to get the UIImageView from the cell?
There's no UIImageView where you're actually showing the image.
It should be something like this:
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
NSURL *profilePictureURL = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large", fbIdString]];
NSData *picData = [NSData dataWithContentsOfURL:profilePictureURL];
UIImageView *fbPicImageView = (UIImageView *)[self.view viewWithTag:1001];
[fbPicImageView setImage:[UIImage imageWithData:picData]];
}

Related

Set UITableview cell image from url in iOS

I am setting image on UITableViewCell using image url ,but the images doesn't get load unless i scrolls the UITableView.Here is the code that i have been using,i got to know about SDWeb Image library to download images from url,but i does;t want to use any library.Please tell me what aim doing wrong in this.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
NSDictionary *dictCard=[cardsDetailsArray objectAtIndex:indexPath.row];
UILabel *nameLabel = (UILabel *)[cell viewWithTag:10];
UILabel *dateLabel = (UILabel *)[cell viewWithTag:11];
UIImageView *cellImage=(UIImageView *)[cell viewWithTag:0];
CGSize firstSize=CGSizeZero;
if([[dictCard objectForKey:#"orientation"]isEqualToString:#"1"]){
[cellImage setFrame:CGRectMake(0, 0, 75, 68)];
firstSize=CGSizeMake(75,68);
}
if([[dictCard objectForKey:#"orientation"]isEqualToString:#"0"]){
[cellImage setFrame:CGRectMake(0, 0, 107, 72)];
firstSize=CGSizeMake(107,72);
}
[cellImage setBackgroundColor:[UIColor clearColor]];
NSString *string=[dictCard objectForKey:#"email_sent"];
NSArray *items = [string componentsSeparatedByString:#","];
dateLabel.text=[dictCard objectForKey:#"date"];
nameLabel.text=[NSString stringWithFormat:#"Sent to %d People",[items count]];
NSURL* url = [NSURL URLWithString:(NSString *) [dictCard objectForKey:#"card_thumbnail"]];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,
NSData * data,
NSError * error) {
if (!error){
UIImage* image = [[UIImage alloc] initWithData:data];
//i am scaling the image here
UIImage *imageScale=[self imageWithImage:image scaledToSize:firstSize];
[cellImage setImage:imageScale];
}
}];
return cell;
}
I have also added [__tableViewDraft reloadData];after setting the cell image but due to this my cell keeps on changing its cell image.
Once the image has been downloaded, you need to ask iOS to refresh the cell. Check out reloadRowsAtIndexPaths:withRowAnimation:, among others.
Typically you might have have cells backed by CoreData objects and download and save the image to the managed object. You'd then have an NSFetchedResultsControllerDelegate trigger an update when the managed object changes, refreshing the row.

Images load table is very slow [duplicate]

This question already has answers here:
UITableview with images scroll very slow
(6 answers)
Closed 9 years ago.
i am getting data from server that contains some images i get properly from url and set it to the tablview cell correctly done.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
AppDelegate * delegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
static NSString *CellIdentifier = #"Cell";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text=[delegate.firstArray objectAtIndex:indexPath.row];
NSLog(#"%#",delegate.thirdArray);
url = [NSURL URLWithString:[NSString stringWithFormat:#"%#",[delegate.thirdArray objectAtIndex:indexPath.row]]];
data = [[NSData alloc]initWithContentsOfURL:url];
UIImage * img=[UIImage imageWithData:data];
cell.imageView.image=img;
return cell;
}
in delegate.thirdArray contais this url
"http://awe.com/app/images/can.png",
"http://awe.com/app/images/card.png",
"http://awe.com/app/images/tp.png",
"http://awe.com/app/images/tricks.png"
images load properly but it will take some time to load that image and scroll the tableview it will very slow i want it to be fast how may i do this.
Load your images using [NSURLConnection sendAsynchronousRequest:queue:completionHandler: then use NSCache to prevent downloading the same image again and again.
As suggested by many developers go for SDWebimage and it does include the above strategy to download the images files .You can load as many images you want and the same URL won't be downloaded several times as per the author of the code
Example on [NSURLConnection sendAsynchronousRequest:queue:completionHandler:
NSURL *url = [NSURL URLWithString:#"your_URL"];
NSURLRequest *myUrlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest: myUrlRequest queue: queue completionHandler: ^ (NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length] > 0 && error == nil)
//doSomething With The data
else if (error != nil && error.code == ERROR_CODE_TIMEOUT)
//time out error
else if (error != nil)
//download error
}];
Then use NSCache...
For further explanation: READ HERE
you have to load images asynchronously so tableview can load fast here in your code tableview take so much time because it load image for every cell.
Please check below answer you can find how to load images asynchronously.
https://stackoverflow.com/a/15377082/1713478
Please change url with your url
hope your problem will solved.
Download AFNetworking from this link
https://github.com/AFNetworking/AFNetworking
and then add files to your project and then in .m file
#import "UIImageView+AFNetworking.h"
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
AppDelegate * delegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
static NSString *CellIdentifier = #"Cell";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text=[delegate.firstArray objectAtIndex:indexPath.row];
NSLog(#"%#",delegate.thirdArray);
url = [NSURL URLWithString:[NSString stringWithFormat:#"%#",[delegate.thirdArray objectAtIndex:indexPath.row]]];
[cell.imageView setImageWithURL:url];
return cell;
}
Another answer is to use the amazing SDWebImage framework. It will load your images asynchronously and cache them so if the user has to load the same image again he won't have to download it again.
Here is the link to the framework :
https://github.com/rs/SDWebImage
Here is the code for your cell :
#import <SDWebImage/UIImageView+WebCache.h>
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
AppDelegate * delegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
static NSString *CellIdentifier = #"Cell";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text=[delegate.firstArray objectAtIndex:indexPath.row];
NSLog(#"%#",delegate.thirdArray);
url = [NSURL URLWithString:[NSString stringWithFormat:#"%#",[delegate.thirdArray objectAtIndex:indexPath.row]]];
[cell.imageView setImageWithURL:url];
// [cell.imageView setImageWithURL:url placeholderImage:[UIImage imageNamed:#"placeholder.png"]]; if you want to add a placeholder image
return cell;
}

how to show image in table cell through json parsing

NSURL *url = [NSURL URLWithString:#"yourimage"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[[UIImage alloc] initWithData:data] autorelease];
This code i used to get the image but how to show it in table cell.
try this,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSURL *url = [NSURL URLWithString:[imageArray objectAtIndex: [indexPath row]]];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[[UIImage alloc] initWithData:data] autorelease];
[[cell imageView] setImage:img];
return cell;
}
FirstLy You need To parse That JSON file In Your iOS Application.
I guess You get Some URL from That JSON for The Image So You need To Download Image Form That Prased URL and Can set That IMage Over ANy UIIMageView and you can set That UIIMageView to The Content View Of UITablViewCell.
Here You Need To Just Manage One THing Suppose You have Many Images To be Downlaod Form The Particular path.So You should Take Care of The UI Interaction also
Here Is Good Example Of How TO download Images form The URL and set That DownLoaded Image Over The UIImageView and set That UIImageView on to the ContentView of UITableViewcell.In this Example you'll also see The Way of How Can you Add The These Images Over The TableViewcEll.
Here Is The Link For That Example
I hope It may help You.
You can do it with
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
[[cell imageView] setImage:img];
But thats probably not going to run very well because you're downloading the images synchronously and that will most likely make your app stutter.
You should use lazy loading for the images, for an example take a look at
http://developer.apple.com/library/ios/#samplecode/LazyTableImages/Introduction/Intro.html
This works for me:
NSURL *url = [NSURL URLWithString:[aTweet objectForKey:#"profile_image_url"]];
NSData *imgData = [NSData dataWithContentsOfURL:url];
cell.imageView.image = [UIImage imageWithData:imgData];

Cancel Selector in UITableViewCell

I have scenario that in which i am using selector in TableViewCell as bellow and when I click on back button in my view I want to cancel that selector and I am sending dictionary as object in Selector
My code is as bellow
In Header File
NSMutableDictionary* photoDict;
NSMutableDictionary* dictImages;
In .M file
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(cell==nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
[[NSBundle mainBundle]loadNibNamed:#"MyCellNib" owner:self options:Nil];
cell = detailChainObj;
}
NSString* avatarURL =#"image_Url"; //Any url of image for cell.
NSString *key =[[NSString alloc] initWithFormat:#"Key%d%d",indexPath.section,indexPath.row];
dictImages = [NSDictionary dictionaryWithObjectsAndKeys:imageViewCell,#"Img",imgURL,#"imgURL",key,#"key", nil];
[self performSelectorInBackground:#selector(DownloadLinkzImageOfUser:) withObject:dictImages];
if([photoDic valueForKey:keyAvt])
{
NSData* data = (NSData*)[photoDic valueForKey:key];
imageViewCell.image = [UIImage imageWithData:data];
}
else
{
[self performSelectorInBackground:#selector(DownloadImagesForCell:) withObject:dictImages];
}
}
//
-(void)DownloadImagesForCell:(NSDictionary *)result
{
UIImageView* img = (UIImageView*)[result objectForKey:#"Img"];
NSString* urlAvt = [result valueForKey:#"imgURL"];
if([urlAvt isEqualToString:#"No Image"])
{
img.image = [UIImage imageNamed:#"noimg.png"];
}
else
{
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgURL]];
img.image = [UIImage imageWithData:data];
[photoDic setValue:data forKey:[NSString stringWithFormat:#"%#",[result valueForKey:#"key"]]];
}
}
Now I want to cancel this selecter when I press back button
and please keep in mind that I have already use
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:#selector(DownloadImagesForCell:) object:dictImages];
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsobject_Class/Reference/Reference.html
I guess this method works for performSelector:withObject:afterDelay: only.

Loading an image into UITableViewCell from an NSArray

I have several hunderd .jpgs in /Resources within an iOS project.
Here is the viewDidLoad method:
- (void)viewDidLoad {
NSArray *allPosters = [[NSBundle mainBundle] pathsForResourcesOfType:#"jpg" inDirectory:#"."];
[super viewDidLoad];
}
The above successfully loads all of the .jpgs into an NSArray.
I simply need to display all of the .jpgs within this array in UITableViewCells in a UITableView
Here is the -(UITableViewCell *)tableView:cellForRowAtIndexPath: method:
-(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
NSDictionary *posterDict = [allPosters objectAtIndex:indexPath.row];
NSString *pathToPoster= [posterDict objectForKey:#"image"];
UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell ==nil ) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]autorelease];
}
UIImage *theImage = [UIImage imageNamed:pathToPoster];
cell.ImageView.image = [allPosters objectAtIndex:indexPath.row];
return cell;
}
I know the issue is with cell.ImageView.image, but am not sure what the issue is? How can I grab each .jpg from the array and display in each row?
NSArray *allPosters = [[NSBundle mainBundle] pathsForResourcesOfType:#"jpg" inDirectory:#"."];
This will give you an array of paths (as suggested by the method name). Those paths are NSStrings.
But you are assigning this array to a local variable, and this variable will be gone after you left viewDidLoad.
so you have to change it into something like this:
allPosters = [[[NSBundle mainBundle] pathsForResourcesOfType:#"jpg" inDirectory:#"."] retain];
Another one:
NSDictionary *posterDict = [allPosters objectAtIndex:indexPath.row];
NSString *pathToPoster= [posterDict objectForKey:#"image"];
And this would definitely crash if you would have assigned the array correctly.
Change it into
NSString *pathToPoster = [allPosters objectAtIndex:indexPath.row];
Next one:
UIImage *theImage = [UIImage imageNamed:pathToPoster];
cell.ImageView.image = [allPosters objectAtIndex:indexPath.row];
UIImages imageNamed: doesn't work with paths, it needs filenames. And of course you want to assign the real image to the imageview and not the path to the poster. So change it:
UIImage *theImage = [UIImage imageNamed:[pathToPoster lastPathComponent]];
cell.imageView.image = theImage;
Try using [UIImage imageWithContentsOfFile:pathToPoster] rather than imageNamed. And set the value to the UIImage object.
It's probably just a typo, but it should be:
//lowercase "i" in imageView
cell.imageView.image = [allPosters objectAtIndex:indexPath.row];
Also- you are creating UIImage *theImage, but then you don't use it. What's going on there?