how to post on facebook friends wall using fbrequest programmatically in iphone? - iphone

I searched every where but not getting the single hint how to do that....i got some code also but it is not working ... can anyone suggest me any tutorial or sample code to do that !!! thanks in advance
i am trying following code::
-(void)inviteFriend:(CustomButton *)sender
{
NSString *str=[NSString stringWithFormat:#"%#/feed",sender.inviteUserId];
if (FBSession.activeSession.isOpen)
{
//UIImage *image = [UIImage imageNamed:#"testImage.png"];
hudApp = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hudApp.labelText = #"Page Sharing...";
[self performSelector:#selector(timeout:) withObject:nil afterDelay:60*5];
// NSString *fbMessage = [NSString stringWithFormat:#"test"];
NSString *fbMessage = #"hello testing";
NSMutableDictionary* params=[NSDictionary dictionaryWithObjectsAndKeys:fbMessage, #"message", FBSession.activeSession.accessToken, #"access_token", nil];
NSLog(#"feed::%#",str);
[FBRequestConnection startWithGraphPath:str
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result,NSError *error) {
NSLog(#"result::%#",result);
if(error)
{
NSLog(#"fail : %#",error.localizedDescription);
hudApp.labelText = [NSString stringWithFormat:#"%#",error.localizedDescription];
}
else
{
NSLog(#"Success facebook post");
hudApp.labelText = [NSString stringWithFormat:#"Success"];
// txtView.text = #"success";
NSLog(#"success");
}
hudApp.mode = MBProgressHUDModeCustomView;
[self performSelector:#selector(dismissHUD:) withObject:nil afterDelay:1.0];
}];
}
else
{
NSArray *permissions = [NSArray arrayWithObject:#"publish_stream"];
[FBSession openActiveSessionWithPermissions:permissions allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState state,NSError *error) {
NSLog(#"session.permissions ? : %#", session.permissions);
[self sessionDoneForPageShare:session state:state error:error withuserid:str];
}
];
}
}
-(void)sessionDoneForPageShare:(FBSession *)session state:(FBSessionState)state error:(NSError *)error withuserid :(NSString *)usreid
{
//UIImage *image = [UIImage imageNamed:#"testImage.png"];
NSLog(#"feed::%#",usreid);
hudApp = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hudApp.labelText = #"Page Sharing...";
[self performSelector:#selector(timeout:) withObject:nil afterDelay:60*5];
//NSString *fbMessage = [NSString stringWithFormat:#"test"];
NSString *fbMessage = #"hello testing";
NSLog(#"State : %d **** Facebook Message : %#",state,fbMessage);
// NSMutableDictionary * params = [NSMutableDictionary dictionaryWithObjectsAndKeys: fbMessage, #"message", nil];
NSMutableDictionary* params=[NSDictionary dictionaryWithObjectsAndKeys:fbMessage, #"message", FBSession.activeSession.accessToken, #"access_token", nil];
[FBRequestConnection startWithGraphPath:usreid
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(error)
{
NSLog(#"fail : %#",error.localizedDescription);
// txtView.text = [NSString stringWithFormat:#"%#",error.localizedDescription];
NSLog(#"%#",[NSString stringWithFormat:#"%#",error.localizedDescription]);
hudApp.labelText = [NSString stringWithFormat:#"%#",error.localizedDescription];
}
else
{
NSLog(#"Success facebook post");
hudApp.labelText = [NSString stringWithFormat:#"Success"];
//txtView.text = #"success";
NSLog(#"success");
}
hudApp.mode = MBProgressHUDModeCustomView;
[self performSelector:#selector(dismissHUD:) withObject:nil afterDelay:1.0];
}];
}

In order to post to a friend's wall, you need to make a request to /{friend_id}/feed. However, Facebook has disabled posting to friends' wall since February 6, 2013:
Removing ability to post to friends walls via Graph API
We will remove the ability to post to a user's friends' walls via the Graph
API. Specifically, posts against [user_id]/feed where [user_id] is
different from the session user, or stream.publish calls where the
target_id user is different from the session user, will fail. If you
want to allow people to post to their friends' timelines, invoke the
feed dialog. Stories that include friends via user mentions tagging or
action tagging will show up on the friend’s timeline (assuming the
friend approves the tag). For more info, see this blog post.

Related

Not able to post on Facebook using Facebook sdk in iOS 7

I am getting an issue while posting a feed on Facebook using Facebook sdk in ios7.
I have copied the code from Facebook samples provided on Github. But whenever I tried to post on Facebook, a message appears as "An error occurred. Please try again later". And then I have to close the web view.
Please find the code below:
NSMutableDictionary *params123 = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"Roasted pumpkin seeds", #"name",
#"Healthy snack.", #"caption",
#"Crunchy pumpkin seeds roasted in butter and lightly salted.", #"description",
#"http://example.com/roasted_pumpkin_seeds", #"link",
#"http://i.imgur.com/g3Qc1HN.png", #"picture",
nil];
// Show the feed dialog
[FBWebDialogs presentFeedDialogModallyWithSession:nil
parameters:params123
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
// An error occurred, we need to handle the error
// See: https://developers.facebook.com/docs/ios/errors
NSLog(#"Error publishing story: %#", error.description);
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
// User cancelled.
NSLog(#"User cancelled.");
} else {
// Handle the publish feed callback
NSDictionary *urlParams = [self parseURLParams:[resultURL query]];
if (![urlParams valueForKey:#"post_id"]) {
// User cancelled.
NSLog(#"User cancelled.");
} else {
// User clicked the Share button
NSString *result = [NSString stringWithFormat: #"Posted story, id: %#", [urlParams valueForKey:#"post_id"]];
NSLog(#"result %#", result);
}
}
}
}];
}
Note: I am using the updated version of Facebook sdk for iOS 7
Why do you use a webdialog ?
Here is what I use
NSArray *urlsArray = [NSArray arrayWithObjects:#"myurl1", nil];
NSURL *imageURL = [NSURL URLWithString:#"http://url/to/image.png"];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
NSArray *imagesArray = [NSArray arrayWithObjects:image, nil];
[FBDialogs presentOSIntegratedShareDialogModallyFrom:self
session:nil
initialText:#"My message for facebook"
images:imagesArray
urls:urlsArray
handler:^(FBOSIntegratedShareDialogResult result, NSError *error) {
NSLog(#"Result : %u", result);
if (error != nil) {
NSLog(#"Error : %#", [error localizedDescription]);
}
}];

Facebook sdk fetch friend error

I am new to iOS development. I got an error when fetching the friend from facebook by using the Facebook SDK.Here are my code.
FacebookClass
- (void)fetchFacebookFriend{
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"user_birthday",#"friends_hometown",
#"friends_birthday",#"friends_location",#"friends_work_history",
nil];
if (!FBSession.activeSession.isOpen) {
// if the session is closed, then we open it here, and establish a handler for state changes
[FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
if (error != nil) {
NSLog(#"Failed to retrive facebook friend.");
return;
}
else{
self.myArray = [[NSMutableArray alloc] init];
NSLog(#"permissions::%#",FBSession.activeSession.permissions);
FBRequest *friendRequest = [FBRequest requestForGraphPath:#"me/friends?fields=name,picture,birthday,hometown,location,work"];
[friendRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
appDelegate.myFacebookArray = [[NSMutableArray alloc] init];
for (NSDictionary *fbData in [result objectForKey:#"data"]) {
NSLog(#"%#",fbData);
[self.myArray addObject:fbData];
}
}];
}
}];
return;
}
}
ViewController
- (IBAction)pickFriendPressed:(id)sender {
NSLog(#"##Begin");
[[FacebookClass sharedInstance] fetchFacebookFriend];
NSLog(#"##End");
}
Output
##Begin
##End
Json data
Please help I get the Json data after display the ##End.Thanks
Here you have a code sample that fetches the friends info:
[facebook requestWithGraphPath:#"me/friends"
andParams:[ NSDictionary dictionaryWithObjectsAndKeys:#"picture,id,name,link,gender,last_name,first_name",#"fields",nil]
andDelegate:self];
Remember to:
implement the proper delegate methods
You must call authorize before fetching the friends information. This way the user will be able to login first.
I hope this helps, cheers
Try this:
get friend list using
[FBRequest requestForMyFriends];
FBRequest* friendsRequest = [FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection connection,NSDictionary result,NSError error) { NSArray friends = [result objectForKey:#"data"]; ......
the coding is as follow but main line is [FBRequest requestForMyFriends];
-(void)sessionStateChanged:(FBSession *)session state:(FBSessionState)state error:(NSError *)error {
switch (state) {
case FBSessionStateOpen: {
if (self != nil) {
[[FBRequest requestForMe] startWithCompletionHandler: ^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (error) {
//error
}else{
FBRequest* friendsRequest = [FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,NSDictionary* result,NSError *error) {
NSArray* friends = [result objectForKey:#"data"];
for (int i = 0; i < [arrFacebookFriends count]; i++) {
UserShare *shareObj = [arrFacebookFriends objectAtIndex:i];
[shareObj release];
shareObj = nil;
}
[arrFacebookFriends removeAllObjects];
for (NSDictionary<FBGraphUser>* friend in friends) {
UserShare *shareObj = [[UserShare alloc] init];
shareObj.userName = friend.name;
shareObj.userFullName = friend.username;
shareObj.userId = [friend.id intValue];
NSLog(#"%#",friend.id);
shareObj.userPhotoUrl = [NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?", friend.id];
[arrFacebookFriends addObject:shareObj];
[shareObj release];
}
[self StopSpinner];
[tblFacebookFriends reloadData];
}];
}
}];
}
FBCacheDescriptor *cacheDescriptor = [FBFriendPickerViewController cacheDescriptor];
[cacheDescriptor prefetchAndCacheForSession:session];
}
break;
case FBSessionStateClosed: {
[self StopSpinner];
UIViewController *topViewController = [self.navigationController topViewController];
UIViewController *modalViewController = [topViewController modalViewController];
if (modalViewController != nil) {
[topViewController dismissViewControllerAnimated:YES completion:nil];
}
//[self.navigationController popToRootViewControllerAnimated:NO];
[FBSession.activeSession closeAndClearTokenInformation];
[self performSelector:#selector(showLoginView) withObject:nil afterDelay:0.5f];
}
break;
case FBSessionStateClosedLoginFailed: {
[self StopSpinner];
[self performSelector:#selector(showLoginView) withObject:nil afterDelay:0.5f];
}
break;
default:
break;
}
[[NSNotificationCenter defaultCenter] postNotificationName:SCSessionStateChangedNotificationFL object:session];
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:#"Error: %#", [FacebookFriendsListViewController FBErrorCodeDescription:error.code]] message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
}
see my accepted this answer on How to get the list of friend without opening FBFriendPickerViewController iOS

iOS Facebook SDK 3.2 Image Publish w/Description Open Graph

No matter what I try I cannot get my description to show up on Facebook. I used the debugger and all is well with the generated link and the URL is populated with the appropriate data. The picture is uploaded fine, but the description is not there. Is there something I need to setup in Facebook settings for the app?
Here is the relevant code:
- (id<FBPost>)outfitObjectForOutfit{
id<FBPost> result = (id<FBPost>)[FBGraphObject graphObject];
NSString *format =
#"http://mysite.mobi/app/fbOpen.php?"
#"og:title=%#&og:description=%%22%#%%22&"
#"og:caption=%%22%#%%22&"
#"og:image=http://mysite.mobi/images/transBlank.png&"
#"body=%#";
result.url = [NSString stringWithFormat:format,
#"New Post Title",fldDescription.text,fldDescription.text,fldDescription.text];
return result;
}
And the portion that publishes to FB:
- (void)postOpenGraphActionWithPhotoURL:(NSString*)photoURL
{
id<FBPost> outfitObject = [self outfitObjectForOutfit];
id<FBPostOutfit> action =
(id<FBPostOutfit>)[FBGraphObject graphObject];
action.outfit=outfitObject;
if (photoURL) {
NSMutableDictionary *image = [[NSMutableDictionary alloc] init];
[image setObject:photoURL forKey:#"url"];
NSMutableArray *images = [[NSMutableArray alloc] init];
[images addObject:image];
action.image = images;
}
[FBSettings setLoggingBehavior:[NSSet
setWithObjects:FBLoggingBehaviorFBRequests,
FBLoggingBehaviorFBURLConnections,
nil]];
NSLog(#"%#",action);
NSMutableDictionary *params = [NSMutableDictionary dictionary];
[params setObject:fldDescription.text forKey:#"message"];
[FBRequestConnection startForPostWithGraphPath:#"me/appnamespace:action"
graphObject:action
completionHandler:
^(FBRequestConnection *connection, id result, NSError *error) {
NSString *alertText;
if (!error) {
alertText = [NSString stringWithFormat:
#"Posted Open Graph action, id: %#",
[result objectForKey:#"id"]];
} else {
alertText = [NSString stringWithFormat:
#"error: domain = %#, code = %d",
error.domain, error.code];
NSLog(#"%#",error);
}
[[[UIAlertView alloc] initWithTitle:#"Result"
message:alertText
delegate:nil
cancelButtonTitle:#"Thanks!"
otherButtonTitles:nil]
show];
}
];
}
I figured out my problem. I was confusing what the Facebook examples did (activity publishing) with publishing to a user's wall. This was all that I had to do to get it to work:
NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
[params setObject:fldDescription.text forKey:#"message"];
[params setObject:UIImagePNGRepresentation(userImage) forKey:#"picture"];
[FBRequestConnection startWithGraphPath:#"me/photos"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error)
{
if (error) {
[[[UIAlertView alloc] initWithTitle:#"Result"
message:#"Sorry there was an error posting to Facebook."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil]
show];
}
}];
I should also mention that I had to go into the opengraph settings for my app and allow user messages and user generated photos.

Facebook Wall Post just after Facebook Signup iOS- facebook SDK 3.2

Facebook SDK 3.2
I need to post a wall post on facebook just after sign-in with faceboook.
Here is the Code i am using:
Here i have a opened the Session For Facebook:
- (IBAction)FBSignup:(id)sender {
[[AppDelegate sharedObject] openSession:^(FBSession *session, FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
}];
}
On State Change, I am populating Data with [self populateUserDetails] and then trying to post on facebook wall as well with [self postOnFB] but there is no post on facebook wall.
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen:
[self populateUserDetails];
[self postOnFB];
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
break;
}
[[NSNotificationCenter defaultCenter]
postNotificationName:SCSessionStateChangedNotification
object:session];
if (error) {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
Here i am populting data with the facebook user object where i need to.
- (void)populateUserDetails
{
if (FBSession.activeSession.isOpen) {
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
///////////////////////////////
// Populating Data Where Needed
///////////////////////////////
// [self postOnFB];
}
}];
}
}
Here i try to post the wall post with [self postOnFB] it gives error:
Terminating app due to uncaught exception
'com.facebook.sdk:InvalidOperationException', reason: 'FBSession: It
is not valid to reauthorize while a previous reauthorize call has not
yet completed.
Here i am posting to the wall.
- (void)postOnFB{
// Ask for publish_actions permissions in context
if ([FBSession.activeSession.permissions
indexOfObject:#"publish_actions"] == NSNotFound) {
// No permissions found in session, ask for it
[FBSession.activeSession requestNewPublishPermissions:[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
[self fbPostSettings];
}
}];
} else {
// If permissions present, publish the story
[self fbPostSettings];
}
}
setting parameters for facebook wall post:
- (void)fbPostSettings{
NSDictionary * facebookParams = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
kFacebookPostLink, #"link",
kFacebookPostImage, #"picture",
kFacebookPostName, #"name",
kFacebookPostCaption, #"caption",
kFacebookPostDescription, #"description",
nil];
[FBRequestConnection startWithGraphPath:#"me/feed"
parameters:facebookParams
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
NSString *alertText;
if (error) {
alertText = [NSString stringWithFormat:
#"error: domain = %#, code = %d",
error.domain, error.code];
} else {
alertText = [NSString stringWithFormat:
#"Posted action, id: %#",
[result objectForKey:#"id"]];
}
NSLog(#"%#",alertText);
}];
}
- (void)sessionStateChanged:(NSNotification*)notification {
[self populateUserDetails];
}
If i call postOnFB on some button action selector (after completion of data population through facebook user object), it post fine on the wall. But i need to post it just after i get the user object in startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary *user, NSError *error) method.
Please help. Thank you everyone :)
Instead of opening session and then requesting publish permissions, directly ask for publish permissions to open the session
[FBSession openActiveSessionWithPublishPermissions:[NSArray arrayWithObjects:#"publish_stream",
nil] defaultAudience:FBSessionDefaultAudienceEveryone allowLoginUI:YES completionHandler:^(FBSession *session,
FBSessionState state, NSError *error) {
if (FBSession.activeSession.isOpen && !error) {
[self fbPostSettings];
}];

How to tag friends in your Facebook wall post...?

I am trying to tag some of my friends in my wall post and I am sending the following parameters but this posts to my wall the FB ids I provide do not get attached to the post...
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"Test 2 ",#"message",
#"100004311843201 , 1039844409", #"to",
#"http://www.google.com", #"link",
#"Test", #"name",
nil];
[self.appDelegate.facebook requestWithGraphPath:#"me/feed" andParams:params andHttpMethod:#"POST" andDelegate:self];
Any help is appreciated...
To tag a friend in ur fb status ..you need "facebook id" of your friend by using FBFriendPickerViewController and "place id" using FBPlacePickerViewController.
Following code will help you.
NSString *apiPath = nil;
apiPath = #"me/feed";
if(![self.selectedPlaceID isEqualToString:#""]) {
[params setObject:_selectedPlaceID forKey:#"place"];
}
NSString *tag = nil;
if(mSelectedFriends != nil){
for (NSDictionary *user in mSelectedFriends) {
tag = [[NSString alloc] initWithFormat:#"%#",[user objectForKey:#"id"] ];
[tags addObject:tag];
}
NSString *friendIdsSeparation=[tags componentsJoinedByString:#","];
NSString *friendIds = [[NSString alloc] initWithFormat:#"[%#]",friendIdsSeparation ];
[params setObject:friendIds forKey:#"tags"];
}
FBRequest *request = [[[FBRequest alloc] initWithSession:_fbSession graphPath:apiPath parameters:params HTTPMethod:#"POST"] autorelease];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
[SVProgressHUD dismiss];
if (error) {
NSLog(#"Error ===== %#",error.description);
if (_delegate != nil) {
[_delegate facebookConnectFail:error requestType:FBRequestTypePostOnWall];
}else{
NSLog(#"Error ===== %#",error.description);
}
}else{
if (_delegate != nil) {
[_delegate faceboookConnectSuccess:self requestType:FBRequestTypePostOnWall];
}
}