Integration error while posting message on friends wall? - iphone

i m using facebook_skd_3.1 (Xcode ios 4.5) i got the friends list by calling
FBFriendPickerViewController, on clicking done button i have tried to post the message
on the selected friends wall but i got this error :-
Warning: Attempt to dismiss from view controller
while a presentation or dismiss is in progress!
2012-12-06 19:37:09.187 ........project[5474:19a03] Error: HTTP status code: 403
error in the alert view
error =Error Domain=com.facebook.sdk code=5" ..........
message = "(#200)the user hasn't authorized the application to perform this action";
type = OAuthException
};
};
code=403;
com.acebook.sdk:HTTPStatuscode=403}
code :-
-(void)facebookViewControllerDoneWasPressed:(id)sender {
NSString* userid;
for (id<FBGraphUser> user in self.friendPickerController.selection)
{
NSLog(#"\nuser=%#\n", user);
userid = user.id;
}
NSMutableDictionary* dictaram = [[NSMutableDictionary alloc]
initWithObjectsAndKeys:#"like this!", #"message", nil];
[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:#"%#/feed", userid]
parameters:params HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Shared"
message:[NSString stringWithFormat:# %#! error=%#", fbUserName, error]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
];
[self dismissModalViewControllerAnimated:YES];
Do i need some permissions or there is some coding error please help.
thanks in advance.

Please dismiss viewcontroller after some delay.

I have figured it by re authorizing the permissions as follows in delegate i have read permissions for session so that didn't worked for posting. write the following code to in the ButtonAction and you will get the proper output.
NSArray *permissions =[NSArray arrayWithObjects:#"publish_actions",#"publish_stream",#"manage_friendlists", nil];
[[FBSession activeSession] reauthorizeWithPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
/* handle success + failure in block */
}];

Related

FBWebDialogs presentRequestsDialogModallyWithSession is not working?

This code is not generating notification on friend's end.But sending successully generating no error.I am building a app for Game url on friend to invite them to play.i have written below code to send url.it's working fine and not generating no error but user is not getting any request for App.
//Fbwebdialog generating no error
[FBWebDialogs presentRequestsDialogModallyWithSession:[FBSession activeSession]
message:[NSString stringWithFormat:#"I just smashed friends! Can you beat it?"]
title:nil
parameters:params
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
// Case A: Error launching the dialog or sending request.
NSLog(#"Some errorr: %#", [error description]);
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:#"Invitiation Sending Failed" message:#"Unable to send inviation at this Moment, please make sure your are connected with internet" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alrt show];
} else {
if (![resultURL query]) {
return ;
NSLog(#"User canceled request.");
} else {
NSDictionary *params = [self parseURLParams:[resultURL query]];
NSMutableArray *recipientIDs = [[NSMutableArray alloc] init];
for (NSString *paramKey in params){
if ([paramKey hasPrefix:#"to["]){
[recipientIDs addObject:[params objectForKey:paramKey]];
}
}
if ([params objectForKey:#"request"]){
NSLog(#"Request ID: %#", [params objectForKey:#"request"]);
NSArray *requestIDs=[params objectForKey:#"request"];
}
if ([recipientIDs count] > 0){
//[self showMessage:#"Sent request successfully."];
//NSLog(#"Recipient ID(s): %#", recipientIDs);
// punGameViewController *pun=[[punGameViewController alloc]initWithNibName:#"punGameViewController" bundle:nil];
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:#"Success!" message:#"Successfully send" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alrt show];
// [self.navigationController pushViewController:pun animated:YES];
}
}
}
}];
//end of code here
check it find the reason not generating notification.
I found my answer to this question on a previously answered S/O question. Basically, you need to set the App Store Id and Bundle Id in the Facebook App settings in order for invites to get sent. You can find that info: here
Notifications sent by your app is only received on mobile devices if your app is a game. If your app is not a game, notifications are still delivered to the App Center on the desktop.

Does not receive any "Request" after sending out from iOS Facebook SDK

I'm following these two tutorials in Facebook developer website
https://developers.facebook.com/docs/tutorials/ios-sdk-games/requests/
https://developers.facebook.com/docs/howtos/send-requests-using-ios-sdk/#step2
These are my codes:
[FBWebDialogs presentRequestsDialogModallyWithSession:nil
message:[NSString stringWithFormat:#"I just smashed %u friends! Can you beat it?", score]
title: nil
parameters:params
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error)
{
if (error)
{
// Case A: Error launching the dialog or sending request.
UIAlertView* alert = [[UIAlertView alloc] initWithTitle: #"Facebook" message: error.description delegate: nil cancelButtonTitle: #"Ok" otherButtonTitles: nil];
[alert show];
[alert release];
}
else
{
if (result == (FBWebDialogResultDialogCompleted))
{
// Handle the publish feed callback
NSDictionary *urlParams = [self parseURLParams:[resultURL query]];
if ([urlParams valueForKey: #"request"])
{
// User clicked the Share button
NSLog(#"Send");
}
}
}
}];
Problem is after I send out the request, my friend told me that he doesn't receive any notification/request in FB Notification Center site. Does anyone know why?
These are the things I've done:
I've setup properly in info.plist and the Facebook App.
I'm not using Sandbox mode.
My current application is able to log in and post to wall.
I've publish_actions permission.
I did not received any error or warning.
I found my solution here:
Facebook App Requests aren't shown on iOS devices?
It is because I didn't set the iPhone App ID and iPad App ID
Use following method, it will help you :
-(void)openFacebookAuthentication
{
NSArray *permission = [NSArray arrayWithObjects:kFBEmailPermission,kFBUserPhotosPermission, nil];
FBSession *session = [[FBSession alloc] initWithPermissions:permission];
[FBSession setActiveSession: [[FBSession alloc] initWithPermissions:permission] ];
[[FBSession activeSession] openWithBehavior:FBSessionLoginBehaviorForcingWebView completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
switch (status) {
case FBSessionStateOpen:
[self getMyData];
break;
case FBSessionStateClosedLoginFailed: {
// prefer to keep decls near to their use
// unpack the error code and reason in order to compute cancel bool
NSString *errorCode = [[error userInfo] objectForKey:FBErrorLoginFailedOriginalErrorCode];
NSString *errorReason = [[error userInfo] objectForKey:FBErrorLoginFailedReason];
BOOL userDidCancel = !errorCode && (!errorReason || [errorReason isEqualToString:FBErrorLoginFailedReasonInlineCancelledValue]);
//Added by Rigel Networks July 2, 2013 to solve Facebook Cancel button popup issue
if(error.code == 2 && ![errorReason isEqualToString:#"com.facebook.sdk:UserLoginCancelled"]) {
UIAlertView *errorMessage = [[UIAlertView alloc] initWithTitle:kFBAlertTitle
message:kFBAuthenticationErrorMessage
delegate:nil
cancelButtonTitle:kOk
otherButtonTitles:nil];
[errorMessage performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:YES];
errorMessage = nil;
}
}
break;
// presently extension, log-out and invalidation are being implemented in the Facebook class
default:
break; // so we do nothing in response to those state transitions
}
}];
permission = nil;
}

How to post to a users wall using Facebook SDK

I want to post some text to a users wall using the facebook sdk in an iOS app.
Is posting an open graph story now the only way to do that?
I've found with open graph stories they are really strange, you can only post things in the format "user x a y" where you preset x and y directly on facebook, like user ata a pizza or user played a game. Setting up each one is pretty laborious too because you have to create a .php object on an external server for each one.
Am I missing something or is there a simpler way to go about this?
Figured it out by browsing the facebook tutorials a bit more.
-(void) postWithText: (NSString*) message
ImageName: (NSString*) image
URL: (NSString*) url
Caption: (NSString*) caption
Name: (NSString*) name
andDescription: (NSString*) description
{
NSMutableDictionary* params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
url, #"link",
name, #"name",
caption, #"caption",
description, #"description",
message, #"message",
UIImagePNGRepresentation([UIImage imageNamed: image]), #"picture",
nil];
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)
{
// If permissions granted and not already posting then publish the story
if (!m_postingInProgress)
{
[self postToWall: params];
}
}
}];
}
else
{
// If permissions present and not already posting then publish the story
if (!m_postingInProgress)
{
[self postToWall: params];
}
}
}
-(void) postToWall: (NSMutableDictionary*) params
{
m_postingInProgress = YES; //for not allowing multiple hits
[FBRequestConnection startWithGraphPath:#"me/feed"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error)
{
if (error)
{
//showing an alert for failure
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Post Failed"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
m_postingInProgress = NO;
}];
}
the easiest way of sharing something from your iOS app is using the UIActivityViewController class, here you can find the documentation of the class and here a good example of use. It is as simple as:
NSString *textToShare = #”I just shared this from my App”;
UIImage *imageToShare = [UIImage imageNamed:#"Image.png"];
NSURL *urlToShare = [NSURL URLWithString:#"http://www.bronron.com"];
NSArray *activityItems = #[textToShare, imageToShare, urlToShare];
UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
[self presentViewController:activityVC animated:TRUE completion:nil];
This will only work on iOS 6 and it makes use of the Facebook account configured in the user settings, and the Facebook SDK is not needed.
You can use Graph API as well.
After all the basic steps to create facebook app with iOS, you can start to enjoy the functionality of Graph API. The code below will post "hello world!" on your wall:
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
...
//to get the permission
//https://developers.facebook.com/docs/facebook-login/ios/permissions
if ([[FBSDKAccessToken currentAccessToken] hasGranted:#"publish_actions"]) {
NSLog(#"publish_actions is already granted.");
} else {
FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
[loginManager logInWithPublishPermissions:#[#"publish_actions"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
//TODO: process error or result.
}];
}
if ([[FBSDKAccessToken currentAccessToken] hasGranted:#"publish_actions"]) {
[[[FBSDKGraphRequest alloc]
initWithGraphPath:#"me/feed"
parameters: #{ #"message" : #"hello world!"}
HTTPMethod:#"POST"]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"Post id:%#", result[#"id"]);
}
}];
}
...
The basic staff is presented here: https://developers.facebook.com/docs/ios/graph
The explorer to play around is here:
https://developers.facebook.com/tools/explorer
A good intro about it: https://www.youtube.com/watch?v=WteK95AppF4

Integrating Facebook SDK for older versions of Xcode to Support both iOS 5 and iOS 6

I am still using XCode 4.3.2 and iOS 5.1 base SDK. What I want to achieve is to integrate Facebook API for iOS 5.0+ devices. Just basic features such as posting on behalf and getting basic user information.
I am assuming that which ever Facebook SDK works on iOS 5, will work on iOS 6, but I am not sure about that.
As a rookie on Facebook Integration, can anybody shed some light on this issue. ( Since I am working on the project, upgrading the XCode and the iOS SDK is not an option)
Which iOS SDK should I be looking into?
Can I support both iOS 5 and
6, with base SDK 5.1 and XCode 4.3?
Is there an API supporting both iOS versions?
Any musts for Facebook Integration?
First of all you read this article published from Facebook developers
http://developers.facebook.com/docs/getting-started/facebook-sdk-for-ios/
in step 1 it will also work for xcode 4.3
you carefully read all steps one by one n implement
In step6 you write code as follow on where Facebook Btn Pressed
- (IBAction)facebookBtnPressed:(id)sender
{
// if it is available to us, we will post using the native dialog
BOOL displayedNativeDialog = [FBNativeDialogs presentShareDialogModallyFrom:self
initialText:[NSString stringWithFormat:#"Here U write code which u want to post on facebook"]
image:[UIImage imageNamed:#"1.jpg"]
url:[NSURL URLWithString:#""]
handler:nil];
if (!displayedNativeDialog)
{
NSString *shareStr = [NSString stringWithFormat:#"Here U write code which u want to post on facebook"];
NSMutableDictionary* params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
shareStr,#"description",
#"sharelink", #"link",
#"ImageName", #"picture",
nil];
[self performPublishAction:^{
[FBRequestConnection startWithGraphPath:#"me/feed" parameters:params HTTPMethod:#"POST" completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (error)
{
NSLog(#"error in post");
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Success" message:#"Post Successfully" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
}];
}];
}
//}
//===set delagate in Viewcontroller.h of mySLComposerSheet
[mySLComposerSheet setCompletionHandler:^(SLComposeViewControllerResult result) {
NSString *output;
switch (result) {
case SLComposeViewControllerResultCancelled:
output = #"Action Cancelled";
break;
case SLComposeViewControllerResultDone:
output = #"Post Successfully";
break;
default:
break;
} //check if everything worked properly. Give out a message on the state.
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Facebook" message:output delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}];
}
- (void) performPublishAction:(void (^)(void)) action {
if ([[FBSession activeSession]isOpen]) {
/*
* if the current session has no publish permission we need to reauthorize
*/
if ([[[FBSession activeSession]permissions]indexOfObject:#"publish_actions"] == NSNotFound) {
[[FBSession activeSession] reauthorizeWithPublishPermissions:[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceOnlyMe
completionHandler:^(FBSession *session, NSError *error) {
action();
}];
}else{
action();
}
}else{
/*
* open a new session with publish permission
*/
[FBSession openActiveSessionWithPublishPermissions:[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceOnlyMe
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if (!error && status == FBSessionStateOpen) {
action();
}else{
NSLog(#"error");
}
}];
}
}

How can we like a url using FB Login?

I want to like a url using a like button as shown in the given link.
At bottom Like button is there
click on the like button will like this page and shows in your facebook profile page under Activity block as shown below:
How can we like a url like that in iPhone App.If user is login with fb then just like if not login then login and then like.
Thanks in Advance.
are you looking for this : Facebook like button
Finally, I have done it.
Code to like Page URL using graph API is as Follows:
- (IBAction)likepageonFB:(id)sender
{
[appDelegate openSession];
NSString *likePage=#"http://www.facebook.com/ipreencekmr";
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
likePage, #"object",[[NSUserDefaults standardUserDefaults] valueForKey:#"token"],#"access_token",
nil];
[FBRequestConnection startWithGraphPath:#"/me/og.likes" parameters:params HTTPMethod:#"POST" completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:#"liked with id %#",[result valueForKey:#"id"]] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
NSLog(#"result is %#",result);
}];
}
You can check this example I have uploaded FBLike Button