Facebook Publish_action is not working for posting - ios

Hi I am trying to post on facebook from my iOS app, before it worked fine. Now I use the latest SDK and following code.
-(void)Authentication{
if (FBSession.activeSession.isOpen) {
[self promptUserWithAccountNameForUploadPhoto];
} else {
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"publish_actions",
nil]; // Tried publish_stream too
[FBSession openActiveSessionWithPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
// if login fails for any reason, we alert
if (error) {
// show error to user.
} else if (FB_ISSESSIONOPENWITHSTATE(status)) {
[self promptUserWithAccountNameForUploadPhoto];
}
}];
}
}
But when it launches Facebook app and login is done, it doen't notify the user about "Post on your behalf", it notifies my app requires your profile details instead.
And when I try to Post like below
-(void)promptUserWithAccountNameForUploadPhoto {
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
NSString * msgStr = [NSString stringWithFormat:#"I have added a new Trip to %#",place];
NSString *imgStr = [NSString stringWithFormat:#"%#assets/upload/flags/%#-213x142.png",appDelegate.ServerURL,country];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"Sharing Tutorial", #"name",
#"Build great social apps and get more installs.", #"caption",
#"Allow your users to share stories on Facebook from your app using the iOS SDK.", #"description",
#"https://developers.facebook.com/docs/ios/share/", #"link",
#"http://i.imgur.com/g3Qc1HN.png", #"picture",
[FBRequestConnection startWithGraphPath:#"/me/feed"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
// Link posted successfully to Facebook
NSLog(#"result: %#", result);
} else {
NSLog(#"%#", error.description);
}
}];
}
}];
}
An error comes as -
message = "(#200) The user hasn't authorized the application to perform this action";

from error code it looks like you don't have permission for share
see facebook error codehere
for get sharing permission refer this page

This error is thrown when you are using publish_actions permission without review. For testing purpose you can always make a test user in Roles column of MyApp in developers.facebook.com and then use it..

Related

Facebook iOS SDK - fetching user albums

I am using Facebook SDK in my iPhone app. I want to find the user's Facebook profile photos, for that I am using the below code:
-(IBAction)FacebookLogin:(id)sender{
if (FBSession.activeSession.isOpen) {
[self findAlbums];
} else {
NSArray *permissions = [[NSArray alloc] initWithObjects:#"user_photos",
nil];
[FBSession openActiveSessionWithPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
// if login fails for any reason, we alert
if (error) {
} else if (FB_ISSESSIONOPENWITHSTATE(status)) {
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
[self findAlbums];
}
}];
}
}];
}
}
-(void)findAlbums {
[FBRequestConnection startWithGraphPath:#"/me/albums"
parameters:nil
HTTPMethod:#"GET"
completionHandler:^(
FBRequestConnection *connection,
id result,
NSError *error
) {
/* handle the result */
NSLog(#"result::%#",result);
}];
}
Out put ---- data = ( );
This does not give any albums in data. The Facebook user logged in have many albums and photos in his profile. Why this happens?
just change the code in find albums to :
[FBRequestConnection startWithGraphPath:#"me/albums"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
// Success! Include your code to handle the results here
NSLog(#"user events: %#", result);
NSArray *feed =[result objectForKey:#"data"];
for (NSDictionary *dict in feed) {
NSLog(#"first %#",dict);
}
} else {
// An error occurred, we need to handle the error
// Check out our error handling guide: https://developers.facebook.com/docs/ios/errors/
NSLog(#"error %#", error.description);
}
}];
you have to add the Facebook credentials(i.e facebook account) you're using to the Facebook developer account settings(i.e as admin or developer) , only then you can access the album's photos through your code

Getting email from facebook user info

Using this methods Facebook iOS 6 - get user info I can get the profile user info from Facebook, but in the json file are not retrieving the email of the user.
Can you helpme to get the email??
Thanks in advance!
You should get email in this way:
[user objectForKey:#"email"]//Where user is FBGraphUser type
Here is the implementation when login is successful
case FBSessionStateOpen: {
NSLog(#"accessToken: %#", session.accessTokenData.accessToken);
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *user,
NSError *error) {
if (error) {
//error
}else{
NSLog(#"%#, %#",[user objectForKey:#"email"], user.description);
}
}];
}
break;
Try this :
facebook = [[Facebook alloc] initWithAppId:[self _APP_KEY] andDelegate:self];
[facebook authorize:[NSArray arrayWithObjects:#"email",nil]];

The operation couldn’t be completed. (com.facebook.sdk error 5.) FACEBOOK VIDEO UPLOAD

I wrote following code for uploading video to facebook from iOS device.
-(void)uploadVideo {
NSLog(#"UPload Videio ");
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"mov"];
NSLog(#"Path is %#", filePath);
NSData *videoData = [NSData dataWithContentsOfFile:filePath];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, #"video.mov",
#"video/quicktime", #"contentType",
#"Video Test Title", #"title",
#"Video Test Description", #"description",
nil];
// [facebook requestWithGraphPath:#"me/videos"
// andParams:params
// andHttpMethod:#"POST"
// andDelegate:self];
if (FBSession.activeSession.isOpen) {
[FBRequestConnection startWithGraphPath:#"me/videos"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(!error) {
NSLog(#"OK: %#", result);
} else
NSLog(#"Error: %#", error.localizedDescription);
}];
} else {
// We don't have an active session in this app, so lets open a new
// facebook session with the appropriate permissions!
// Firstly, construct a permission array.
// you can find more "permissions strings" at http://developers.facebook.com/docs/authentication/permissions/
// In this example, we will just request a publish_stream which is required to publish status or photos.
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"publish_stream",
nil];
//[self controlStatusUsable:NO];
// OPEN Session!
[FBSession openActiveSessionWithPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
// if login fails for any reason, we alert
if (error) {
// show error to user.
} else if (FB_ISSESSIONOPENWITHSTATE(status)) {
// no error, so we proceed with requesting user details of current facebook session.
[FBRequestConnection startWithGraphPath:#"me/videos"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
// [FBRequestConnection setVideoMode:NO];
if(!error) {
NSLog(#"VEEERRRRRRR: %#", result);
} else
NSLog(#"VVEEERRRRREEEERRR: %#", error.localizedDescription);
}];
//[self promptUserWithAccountNameForUploadPhoto];
}
// [self controlStatusUsable:YES];
}];
}
}
This gives me error
The operation couldn’t be completed. (com.facebook.sdk error 5.)
I don't know what is wrong with facebook. It uploads image, text, but in video it gives this error.
NOTE:
It is not due to send again and again, as I also tested by making new account and resetting iOS Device.
sample.mov also exists and works with graph api, but issue is with this SDK.
Thanks.
Few causes for seeing com.facebook.sdk error 5:
Session is is not open. Validate.
Facebook has detected that you're spamming the system. Change video name.
Facebook has a defined limit using the SDK. Try a different app.
Wrong publish permission. Give publish_actions a spin.
more here... ?
Having read this solution. I was able solve this problem.
[FBRequestConnection startWithGraphPath:#"me/videos"
completionHandler:^(FBRequestConnection *connection,
id result, NSError *error)
{
[FBRequestConnection startWithGraphPath:#"me/videos"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(!error)
{
NSLog(#"SUCCESS RESULT: %#", result);
}
else
{
NSLog(#"ERROR: %#", error.localizedDescription);
}
}];
}];
I was having this problem all day when I noticed that my app does not appear in:
Settings App->Facebook->"ALLOW THESE APPS TO USE YOUR ACCOUNT"
This made me realize that posting to Facebook is not permitted by default, you must prompt the user for their permission:
[[FBSession activeSession] requestNewPublishPermissions:#[#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error)
{
if (!error)
{
// UPLOAD VIDEO HERE AND THAT ERROR 5 SHOULD GO AWAY
}
}];

Facebook asks for my approval while posting image from IOS

I am running into some issue while posting image from iOS application which uses Facebook sdk every time i post an image from my application it asks for permission on my actual Facebook account.
here it is my function which posts image to Facebook
- (void) postImageToFB:(UIImage*)image
{
NSLog(#"posImagetoFB was called...");
NSData* imageData = UIImagePNGRepresentation(image);
NSMutableDictionary * params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"This is my drawing!", #"message",
imageData, #"source",
nil];
[FBRequestConnection startWithGraphPath:#"me/photos"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(error)
{
NSLog(#"erro has occured %#",error);
}
if(result)
{
NSLog(#"result is %#",result);
}
}];
}
and here is code i use in order to login into Facebook
- (void)openSession
{
NSArray *permissions = [NSArray arrayWithObjects:#"user_photos",
nil];
[FBSession openActiveSessionWithReadPermissions:nil
allowLoginUI:YES
completionHandler:
^(FBSession *session,
FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
}];
}
Thanks in advance.
I think you should add publish_stream permission to your array like this :
NSArray *permissions = [NSArray arrayWithObjects:#"user_photos",#"publish_stream",nil];
which will allow you to post image without asking for permission again and again.

Facebook iOS SDK 3.5.1: openActiveSessionWithReadPermissions - completion handler called twice

I have a button to share a link. I'm using basically two calls:
openActiveSessionWithReadPermissions and requestNewPublishPermissions.
So this is the button action:
- (IBAction) shareFacebookButtonAction:(id)sender
if (![[FBSession activeSession] isOpen])
{
NSArray *permissions = #[#"read_friendlists", #"email"];
[FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error)
{
if (FB_ISSESSIONOPENWITHSTATE([session state]))
{
[self _prepareShare];
}
else
{
// show alert view with error
}
}];
}
else
{
[self _prepareShare];
}
}
and with this I'm asking for publish permission, if no permissione are found in session
-(void) _prepareShare;
{
if ([FBSession.activeSession.permissions
indexOfObject:#"publish_actions"] == NSNotFound)
{
[FBSession.activeSession
requestNewPublishPermissions:
[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error)
{
if (!error)
{
[self _share];
}
else
{
//error
}
}];
} else
{
[self _share];
}
}
_share just posts something
-(void) _share;
{
NSMutableDictionary *params_dict = [NSMutableDictionary dictionary];
// setting some params
[FBRequestConnection startWithGraphPath:#"me/feed" parameters:params_dict HTTPMethod:#"POST" completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
if (result)
{
// sharing succedeed, do something
}
else if (error)
{
//sharing failed, do something else
}
}];
}
First time I try to share (already logged on FB in iOS6 and app already authorized) completion handler of openActiveSessionWithReadPermissions is being called twice:
once with FBSessionStateOpen and once with FBSessionStateOpenTokenExtended (from the openSessionForPublishPermissions call).
As a consequence, _share is also called twice, first time in the else part of _prepareShare (if I already have publish permissions) and the second time in the completion handler of openSessionForPublishPermissions.
So I have a double post on Facebook wall, just the first time I ever share in the app. I also had a crash report for FBSession: It is not valid to reauthorize while a previous reauthorize call has not yet completed (I couldn't be able to make it happen again).
What is the proper way to handle this situation?
It appears that by design, Facebook SDK retains references to block handlers, even after they have been called. Thus, in your call to openActiveSessionWithReadPermissions the completion handler may be called numerous times, in case the session state changes. See Facebooks comment on this issue here.
As a work around, you might want to implement your own mechanism that ensures the handler is fired only once:
__block FBSessionStateHandler runOnceHandler = ^(FBSession *session,
FBSessionState status,
NSError *error) { /* YOUR CODE HERE */ };
...
[FBSession openActiveSessionWithReadPermissions:YOUR_PERMISSIONS
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
if (runOnceHandler) {
runOnceHandler(session, status, error);
runOnceHandler = nil;
}
}
];
You Can use this
- (IBAction)facebookBasti:(id)sender {
if(FBSession.activeSession.isOpen){
[[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
NSLog(#" Email = %#",[user objectForKey:#"email"]);
}
}];
NSLog(#"POST TO WALL -- %#",FBSession.activeSession.accessToken);
[self publishFacebook];
}
else {
// try to open session with existing valid token
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"publish_actions",#"email",
nil];
FBSession *session = [[FBSession alloc] initWithPermissions:permissions];
[FBSession setActiveSession:session];
if([FBSession openActiveSessionWithAllowLoginUI:NO]) {
// post to wall
[[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
NSLog(#" Email = %#",[user objectForKey:#"email"]);
}
}];
NSLog(#"POST TO WALL -- %#",FBSession.activeSession.accessToken);
[self publishFacebook];
} else {
// you need to log the user
NSLog(#"login");
[FBSession openActiveSessionWithPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
NSLog(#"POST TO WALL -- %#",FBSession.activeSession.accessToken);
[self publishFacebook];
}];
}
}
}
and publishFacebook method
-(void)publishFacebook
{
NSMutableDictionary *postParams2= [[NSMutableDictionary alloc] initWithObjectsAndKeys:
haberLink, #"link",
#"abc.com", #"name",
title, #"caption",
desc, #"description",
nil];
[FBRequestConnection
startWithGraphPath:#"me/feed"
parameters:postParams2
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: #"Shared Facebook"];
[[[UIAlertView alloc] initWithTitle:#"Shared Facebook"
message:alertText
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil]
show];
}
}];
}
Please read Upgrading from 3.0 to 3.1, in particular the paragraph Asking for Read & Write Permissions Separately. It seems like Facebook SDK is not meant to be used this way.
You are now required to request read and publish permission separately (and in that order). Most likely, you will request the read permissions for personalization when the app starts and the user first logs in. Later, if appropriate, your app can request publish permissions when it intends to post data to Facebook.
and
It is important that you do not simply attempt to call the two individual methods back-to-back to replace either of the deprecated functions.
I wonder how you managed to solve this issue. BTW, I get the same crash report (FBSession: It is not valid to reauthorize while a previous reauthorize call has not yet completed).

Resources