How to post images in facebook in iphone app? - iphone

could anyone pls help me to post fotos on facebook using objective c for iphone app.i tried it but its getting terminated when i check with iphone.its working properly in simulator.following is my code i used to post in fb.i use graph api for developing my app.
-(void)fbGraphCallback:(id)sender {
if ((fbGraph.accessToken == nil) || ([fbGraph.accessToken length] == 0)) {
NSLog(#"You pressed the 'cancel' or 'Dont Allow' button, you are NOT logged into Facebook...I require you to be logged in & approve access before you can do anything useful....");
//restart the authentication process.....
[fbGraph authenticateUserWithCallbackObject:self
andSelector:#selector(fbGraphCallback:)
andExtendedPermissions:#"user_photos,user_videos,publish_stream,offline_access,user_checkins,friends_checkins"];
[self.view addSubview:viewshare];
}
else {
NSMutableDictionary *variables = [NSMutableDictionary dictionaryWithCapacity:2];
//imgPicture is my image view name
NSLog(#"the Data::%#\n",imgPicture.image);
FbGraphFile *graph_file = [[FbGraphFile alloc] initWithImage:imgPicture.image];
[variables setObject:graph_file forKey:#"file"];
[variables setObject:[NSString stringWithFormat:#"%#", txtComment.text] forKey:#"message"];
FbGraphResponse *fb_graph_response = [fbGraph doGraphPost:#"me/photos" withPostVars:variables];
NSLog(#"postPictureButtonPressed: %#", fb_graph_response.htmlResponse);
NSLog(#"Now log into Facebook and look at your profile & photo albums...");
txtComment.text=#" ";
[txtComment setHidden:YES];
[lblcmt setHidden:YES];
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:#"Successfully posted...Now log into Facebook & look at your profile" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
[fbGraph release];
}

First I check if facebook(the facebook object) has a valid session:
if (![facebook_ isSessionValid]) {
permissions_ = [[NSArray arrayWithObjects:#"read_stream", #"publish_stream", #"offline_access",nil] retain];
[facebook_ authorize:permissions_];
}
When I can guaranty that i'm logged into facebook I post the image like this:
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
image, #"picture",
message, #"message",
nil];
[facebook_ requestWithGraphPath:#"me/photos"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
Finally I check this methods in for being sure if the image post was succesful or not:
-(void)request:(FBRequest *)request didFailWithError:(NSError *)error {
//Error
}
-(void)request:(FBRequest *)request didLoad:(id)result {
//Succes
}

Related

how to post text to friend wall in Facebook in iphone sdk?

i want to post text to friend wall but there is some problem by using this code...
-(IBAction)PostToBuddyWall
{
NSMutableDictionary *postVariablesDictionary = [[NSMutableDictionary alloc] init];
[postVariablesDictionary setObject:#"LOL" forKey:#"name"];
[postVariablesDictionary setObject:#"helllo" forKey:#"message"];
Facebook *fb = [((AppDelegate*)[[UIApplication sharedApplication] delegate]) fbInstance];
[fb requestWithGraphPath:[NSString stringWithFormat:#"%#/feed",self.fbFriendsInvited] andParams:postVariablesDictionary andHttpMethod:#"POST" andDelegate:nil];
NSLog(#"message: %#",postVariablesDictionary);
[postVariablesDictionary release];
UIAlertView *facebookAlter=[[UIAlertView alloc] initWithTitle:#"Message" message:#"Posted successfully on facebook" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil, nil];
[facebookAlter show];
[facebookAlter release];
[self dismissViewControllerAnimated:YES completion:nil];
}
please give the suggestions if u have...
thanks !!
Try this :
NSMutableDictionary *postVariablesDictionary = [[NSMutableDictionary alloc] init];
[postVariablesDictionary setObject:#"LOL" forKey:#"name"];
[postVariablesDictionary setObject:#"helllo" forKey:#"message"];
//Post to friend's wall.
[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:#"%#/feed", self.fbFriendsInvited] parameters: postVariablesDictionary HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
NSLog(#"%#",result);
}];

How to post image along with Text using Graph api?

the below code successfuly post my text on facebook wall now i want to post a image along with text using Below code
- (IBAction)callFacebookAPI:(id)sender
{
[self.txtinputfield resignFirstResponder];
if (txtinputfield.text.length !=0)
{
//create the instance of graph api
objFBGraph = [[FbGraph alloc]initWithFbClientID:FbClientID];
//mark some permissions for your access token so that it knows what permissions it has
[objFBGraph authenticateUserWithCallbackObject:self andSelector:#selector(FBGraphResponse) andExtendedPermissions:#"user_photos,user_videos,publish_stream,offline_access,user_checkins,friends_checkins,publish_checkins,email"];
}
else
{
UIAlertView *objAlert = [[UIAlertView alloc]initWithTitle:#"Alert" message:#"Kindly enter data in the text field" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[objAlert show];
}
}
- (void)FBGraphResponse
{
#try
{
if (objFBGraph.accessToken)
{
SBJSON *jsonparser = [[SBJSON alloc]init];
FbGraphResponse *fb_graph_response = [objFBGraph doGraphGet:#"me" withGetVars:nil];
NSString *resultString = [NSString stringWithString:fb_graph_response.htmlResponse];
NSDictionary *dict = [jsonparser objectWithString:resultString];
NSLog(#"Dict = %#",dict);
NSMutableDictionary *variable = [[NSMutableDictionary alloc]initWithCapacity:1];
[variable setObject:txtinputfield.text forKey:#"message"];
[objFBGraph doGraphPost:#"me/feed" withPostVars:variable];
UIAlertView *objAlert = [[UIAlertView alloc]initWithTitle:#"Alert" message:#"String posted on your wall and you may check the console now" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[objAlert show];
}
}
#catch (NSException *exception) {
UIAlertView *objALert = [[UIAlertView alloc]initWithTitle:#"Alert" message:[NSString stringWithFormat:#"Something bad happened due to %#",[exception reason]] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[objALert show];
}
txtinputfield.text = clearText;
}
I tried some methods but did'nt work for me, i have no experience with Graph Api Any help will be appriated.Thanks
Try like below:
- (IBAction)buttonClicked:(id)sender
{
NSArray* permissions = [[NSArray alloc] initWithObjects:
#"publish_stream", nil];
[facebook authorize:permissions delegate:self];
[permissions release];
}
- (void)fbDidLogin
{
NSString *filePath =pathToImage;
NSData *videoData = [NSData dataWithContentsOfFile:filePath];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, pathToImage,
#"picture/jpeg", #"contentType",
#"Video Test Title", #"title",
#"Video Test Description", #"description",
nil];
[facebook requestWithGraphPath:#"me/photos"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
}
-(void)fbDidNotLogin:(BOOL)cancelled
{
NSLog(#"did not login");
}
- (void)request:(FBRequest *)request didLoad:(id)result
{
if ([result isKindOfClass:[NSArray class]])
{
result = [result objectAtIndex:0];
}
NSLog(#"Result of API call: %#", result);
}
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error
{
NSLog(#"Failed with error: %#", [error localizedDescription]);
}

How to post uiimage instead of image url from fbconnect feed dialog?

I need to post uiimage (screenshot taken from app) instead of url to post in facebook from facebook dialog along with user option to enter text. how it can be achieved. some help is appreciated.
You could try something like this to post the photo part. I'm sure the text is just another field.
#try {
// make sure your permissions are set
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"publish_stream",
nil];
[FBSession openActiveSessionWithPublishPermissions:permissions
defaultAudience:FBSessionDefaultAudienceOnlyMe
allowLoginUI:NO
completionHandler:^(FBSession *session, FBSessionState state, NSError *error){
NSLog(#"completion handler.");
}];
[FBRequestConnection startForUploadPhoto:imageToUpload
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
UIAlertView *tmp = [[UIAlertView alloc]
initWithTitle:#"Success"
message:#"Photo Uploaded!"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Ok", nil];
[tmp show];
} else {
UIAlertView *tmp = [[UIAlertView alloc]
initWithTitle:#"Error"
message:#"Error uploading image to Facebook."
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Ok", nil];
[tmp show];
}
}];
}
#catch (NSException *exception) {
NSLog(#"-----> !! ERROR UPLOADING IMAGE TO FACEBOOK !!");
}
to post image in facebook through fbconnect few steps need to follow with the fbconnect api.
need to login in facebook then it check about the access key and the expiry date.
if those are not nil, there it go to post the image i.e
NSData *imageData = UIImagePNGRepresentation(cellImageView.image);
NSMutableDictionary *params = [[NSMutableDictionary alloc]initWithObjectsAndKeys:#"app name",#"message",imageData,#"source", nil];
[facebook requestWithGraphPath:#"me/photos" andParams:params andHttpMethod:#"POST" andDelegate:self];
if not it go for the access key and expiry key and then to the image post code as written above.
for more download fbconnect api and look at the login and have a look on the code with brakepoints.
for this user need the login delegate and fb request delegate.
also don't forget to initialize facebook obj with app id and to set its delegate self.

Image Post on Facebook?

In my application. I successfully post a image on my Facebook wall (image type JPEG Type). It's work fine in Simulator and and Device also.
But the problem is that When I Capture Image from my iPhone or select an image from library which is captured by camera. It is not Posted on Facebook Wall.
on other hand when i choose any jpeg image (downloaded by internet) from my iPhone library. It post on wall.
In my opinion there is image format problem. Please Guide me
Thanks
My code is here.
-(IBAction)clickButtonClicked
{
// For link post
NSString *Message = [NSString stringWithFormat:#"Testing Iphone App : \"http://www.google.com\" "];
DataClass *obj=[DataClass getInstance];
UIImage *image=[[UIImage alloc]init ];
image= obj.imgFinalImage;
NSMutableDictionary *params1 = [[NSMutableDictionary alloc]init];
[params1 setObject:image forKey:#"source"];
[params1 setObject:Message forKey:#"message"];
NSString *post=#"/me/photos";
[[appDelegate facebook] requestWithGraphPath:post andParams:params1 andHttpMethod:#"POST" andDelegate:self];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message!" message:#"Invitation Send Sucessfully" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
My guess is that you pass the image in the wrong property:
NSMutableDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
sobj.imgFinalImage, #"picture",
Message, #"caption",
nil];
[[appDelegate facebook] requestWithMethodName:#"photos.upload"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
Then make sure you implement the delegate of Facbook request to check if the image is uploaded.
With the graph API you can't send a UIImage directly, you need to send the NSData representation of the UIImage:
NSMutableDictionary *params1 = [[NSMutableDictionary alloc]init];
NSData *imageDate = UIImagePNGRepresentation(obj.imgFinalImage);
[params1 imageDate forKey:#"source"];
[params1 setObject:Message forKey:#"message"];
NSString *post=#"/me/photos";
[[appDelegate facebook] requestWithGraphPath:post andParams:params1 andHttpMethod:#"POST" andDelegate:self];

Cant Post To Facebook with Graph API iPhone

i have implemented this sample code below to get a connection to the user feed post
- (void)viewDidLoad
{
[super viewDidLoad];
facebook = [[Facebook alloc] initWithAppId:#"197765190297119" andDelegate:self];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
facebook.accessToken = [defaults objectForKey:#"FBAccessTokenKey"];
facebook.expirationDate = [defaults objectForKey:#"FBExpirationDateKey"];
}
and this sample code is called when the user logs in... it calls now by a button pressed for check, but dosent do any, perhaps i can get a dialog feed insted
NSString *str=#"Your String to post";
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
str,#"message",
#"Test it!",#"name",
nil];
Facebook *fb = [[Facebook alloc] init];
[fb requestWithGraphPath:#"me/feed" // or use page ID instead of 'me'
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
This is a walkthrough of uploading an image to the facebook wall. I copied this out of an older application, the current facebook API works a little bit different. I think you can see my main point of using a shared facebook object, which you use to do the authentication and also the requests to the API. I took out a few things to make it easier to understand. Apple actually wants you to check for an existing internet connection. I hope it helps.
#synthesize facebook;
//login with facebook
- (IBAction) facebookButtonPressed {
if (!facebook || ![facebook isSessionValid]) {
self.facebook = [[[Facebook alloc] init] autorelease];
NSArray *perms = [NSArray arrayWithObjects: #"read_stream", #"create_note", nil];
[facebook authorize:FACEBOOK_API_KEY permissions:perms delegate:self];
}
else {
[self fbDidLogin];
}
}
//upload image once you're logged in
-(void) fbDidLogin {
[self fbUploadImage];
}
- (void) fbUploadImage
{
NSMutableDictionary * params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
resultImage, #"picture",
nil];
[facebook requestWithMethodName: #"photos.upload"
andParams: params
andHttpMethod: #"POST"
andDelegate: self];
self.currentAlertView = [[[UIAlertView alloc]
initWithTitle:NSLocalizedString(#"Facebook", #"")
message:NSLocalizedString(#"Uploading to Facebook.", #"")
delegate:self
cancelButtonTitle:nil
otherButtonTitles: nil] autorelease];
[self.currentAlertView show];
}
//facebook error
- (void)request:(FBRequest*)request didFailWithError:(NSError*)error
{
[self.currentAlertView dismissWithClickedButtonIndex:0 animated:YES];
self.currentAlertView = nil;
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:NSLocalizedString(#"Error", #"")
message:NSLocalizedString(#"Facebook error message", #"")
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"OK", nil];
[myAlert show];
[myAlert release];
}
//facebook success
- (void)request:(FBRequest*)request didLoad:(id)result
{
[self.currentAlertView dismissWithClickedButtonIndex:0 animated:YES];
self.currentAlertView = nil;
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:NSLocalizedString(#"Facebook", #"")
message:NSLocalizedString(#"Uploaded to Facebook message", #"")
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"OK", nil];
[myAlert show];
[myAlert release];
}