Cannot post to Facebook using iOS app - ios

I am creating an iOS app. I need to post some links to Facebook events using my app. I have integrated Facebook SDK. By using Facebook Graph API, i found the code for the same and it works fine in Graph API Explorer. But it does not working in my app. When trying to post the link to Facebook,it shows the following error. I am using Xcode 7.3 and iOS 9.
error=Error Domain=com.facebook.sdk.core Code=8 "(null)" UserInfo={com.facebook.sdk:FBSDKGraphRequestErrorCategoryKey=0, com.facebook.sdk:FBSDKGraphRequestErrorHTTPStatusCodeKey=403, com.facebook.sdk:FBSDKErrorDeveloperMessageKey=(#200) Insufficient permission to post to target on behalf of the viewer, com.facebook.sdk:FBSDKGraphRequestErrorGraphErrorCode=200, com.facebook.sdk:FBSDKGraphRequestErrorParsedJSONResponseKey={
body = {
error = {
code = 200;
"fbtrace_id" = DWR8SW4K1Ls;
message = "(#200) Insufficient permission to post to target on behalf of the viewer";
type = OAuthException;
};
};
code = 403;
My code is given below.
-(void)postToFacebook
{
if ([[FBSDKAccessToken currentAccessToken] hasGranted:#"publish_actions"]) {
[self post];
// TODO: publish content.
} else {
FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
[loginManager logInWithPublishPermissions:#[#"publish_actions"]
fromViewController:self
handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if(error)
{
NSLog(#"error=%#",error);
}
else{
[self post];
}
//TODO: process error or result.
}];
}
}
-(void)post
{
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:3466734743/feed
parameters:#{ #"link": #"http://www.dhip.in/ofc/metatest.html",}
HTTPMethod:#"POST"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
// Insert your code here
if(error)
{
NSLog(#"error=%#",error);
}
else
{
NSLog(#"success");
}
}];
}
And i have looked into https://developers.facebook.com/docs/ios/ios9 and tried all the combination of LSApplicationQueriesSchemes in my info.plist.Please help me.What is the problem? Why i can't post to Facebook?

SLComposeViewController *fbCompose;
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
fbCompose=[[SLComposeViewController alloc]init];
fbCompose=[SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
[fbCompose setInitialText:#"My Score in AlphaMarics is"];
[fbCompose addImage:image];
[self presentViewController:fbCompose animated:YES completion:nil];
}
[fbCompose setCompletionHandler:^(SLComposeViewControllerResult result)
{
NSString * fbOutput=[[NSString alloc]init];
switch (result){
case SLComposeViewControllerResultCancelled:
fbOutput=#"You Post is cancelled";
break;
case SLComposeViewControllerResultDone:
fbOutput=#"Your post Posted Succesfully";
break;
default:
break;
}
UIAlertView * fbAlert=[[UIAlertView alloc]initWithTitle:#"Warning" message:fbOutput delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[fbAlert show];
}];

Related

Is user_photos needed?

Please excuse the elementary question but I am pretty confused on requesting Facebook permissions for my app. My app allows users to select photos then login to their facebook page and those photos are posted on their timeline. I am requesting manage_pages, publish_pages, and publish_actions. In my developer account I added two testers who are friends of mine and we thoroughly tested the process. Everything works perfectly. But when I created a Test User (the one where facebook creates a generic account) my app doesn't post photos to their wall. I granted the test user the same permissions. I am now wondering if I need to call user_photos as another requested permission. I don't think I do since I am not requesting access to the users photos or albums. I am simply posting photos to their timeline which I thought is what publish_pages and publish_actions does. Can you look at the code and see if you can find what I am doing wrong?
- (IBAction)facebookButtonClicked1:(id)sender
{
if ([self.selectedImages count] > 0)
{
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
login.loginBehavior = FBSDKLoginBehaviorWeb;
[login logInWithPublishPermissions:#[#"publish_actions"]
fromViewController:self
handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
NSLog(#"Process error");
} else if (result.isCancelled) {
NSLog(#"Cancelled");
} else {
NSLog(#"Logged in");
[self shareSegmentWithFacebookComposer];
}
}];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Photos" message:#"You have not selected any photo." delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
}
-(void)shareSegmentWithFacebookComposer{
if ([[FBSDKAccessToken currentAccessToken] hasGranted:#"publish_actions"]) {
[self publishFBPost]; //publish
} else {
NSLog(#"no publish permissions");
}
}
-(void) publishFBPost{
NSMutableArray* photos = [[NSMutableArray alloc] init];
for (NSString* imageFile in self.selectedImages) {
UIImage *image = [UIImage imageWithContentsOfFile:[dataPath stringByAppendingPathComponent:imageFile]];
FBSDKSharePhoto *photo = [[FBSDKSharePhoto alloc] init];
photo.image = image;
photo.userGenerated = YES;
[photos addObject:photo];
}
FBSDKSharePhotoContent *content = [[FBSDKSharePhotoContent alloc] init];
content.photos = [photos copy];
[FBSDKShareDialog showFromViewController:self
withContent:content
delegate:nil];
[FBSDKShareAPI shareWithContent:content delegate:nil];
viewThanks.hidden = NO;
[NSTimer scheduledTimerWithTimeInterval:4.5 target:self selector:#selector(start) userInfo:nil repeats:NO];
FBSDKShareDialog *shareDialog = [FBSDKShareDialog new];
[shareDialog setMode:FBSDKShareDialogModeAutomatic];
[shareDialog setShareContent:content];
[shareDialog show];
}
There were publish_stream permission to upload photos but in the latest SDK publish_actions have replaced publish_actions so you only need publish_actions. And if you want to see the user's photos then you need the user_photos permission.

using Twitter SDK to send tweet failed, but I'dont know why

I'm using Twitter SDK to loggin and tweet. Authenticate it's ok, but when use TWTRComposer with a simple text, the SDK callback return 'TWTRComposerResultDone', but the Simulator/Device show 'The tweet "text" cannot be sent because the connection to Twitter failed.
The debugger show 'plugin com.apple.share.Twitter.post invalidated' but everything aparently is correct.
Is there a bug or I forgot some thing.
My code:
TWTRComposer *composer = [[TWTRComposer alloc] init];
[composer setText:#"some text"];
[composer showWithCompletion:^(TWTRComposerResult result) {
if (result == TWTRComposerResultCancelled) {
NSLog(#"Tweet composition cancelled");
}
else {
NSLog(#"Sending Tweet!");
}
}];
Tweet Using SDK
1. Crearte App on twitter.developer
2. add twitter frameworks like TwitterCore.framework, TwitterKit.framework, Fabric.framework, TwitterKitResources.bundle
3. write below code in tweet button
[[Twitter sharedInstance] startWithConsumerKey:#"YourConsumerKey" consumerSecret:#"YourConsumerSecret"];
[Fabric with:#[[Twitter sharedInstance]]];
[[Twitter sharedInstance] logInWithCompletion:^(TWTRSession *session, NSError *error)
{
if (session)
{
NSLog(#"logged in user with id %#", session.userID);
TWTRComposer *composer = [[TWTRComposer alloc] init];
[composer setText:#"Enter Your Tweet Message"];
//[composer setImage:[UIImage imageNamed:#"fabric"]];
[composer showFromViewController:self completion:^(TWTRComposerResult result) {
if (result == TWTRComposerResultCancelled)
{
NSLog(#"Tweet composition cancelled");
}
else
{
NSLog(#"Sending Tweet!");
UIAlertView *warningAlert = [[UIAlertView alloc] initWithTitle:#"" message:#"Sent Tweet!" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[warningAlert show];
}
}];
}
else
{
// log error
}
}];

How to upload an image on Facebook without staging it in iOS?

This is my code so far to post a custom story with a local Image. The Image shows in the Share Dialog but the post doesn't complete.
NSMutableDictionary<FBOpenGraphObject> *object = [FBGraphObject openGraphObjectForPost];
object.provisionedForPost = YES;
object[#"title"] = #"";
object[#"type"] = #"socialsnooker:game_of_snooker";
object[#"description"] = #"";
object[#"url"] = #"http://socialsnooker.com/opengraph.php";
object[#"image"] = #[#{#"url": newImage, #"user_generated" : #"false" }];
NSArray* images = #[#{#"url": newImage, #"user_generated" : #"true" }];
id<FBOpenGraphAction> action = (id<FBOpenGraphAction>)[FBGraphObject graphObject];
[action setObject:images forKey:#"image"];
[action setObject:object forKey:#"game_of_snooker"];
[action setTags:#[opponent]];
// Tag a place using the place's id
id<FBGraphPlace> place = (id<FBGraphPlace>)[FBGraphObject graphObject];
[place setObjectID:#"36397646443"]; // Q-Masters
[action setPlace:place];
// Check if the Facebook app is installed and we can present the share dialog
FBOpenGraphActionParams *params = [[FBOpenGraphActionParams alloc] init];
params.action = action;
params.actionType = #"socialsnooker:score";
// If the Facebook app is installed and we can present the share dialog
if([FBDialogs canPresentShareDialogWithOpenGraphActionParams:params]) {
// Show the share dialog
[FBDialogs presentShareDialogWithOpenGraphAction:action
actionType:#"socialsnooker:score"
previewPropertyName:#"game_of_snooker"
handler:^(FBAppCall *call, NSDictionary *results, 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 {
// Success
NSLog(#"result %#", results);
}
}];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"App Not Installed"
message:#"The Facebook App couldn't be found on your phone."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
Here is a Screenshot of the Share Dialog
The Image does show up in the Share Dialog and I do get a post ID in return but the action does not get posted on Facebook.
Any help would be greatly appreciated. Thanks.

how to Use Default LoginWithFacebook Button in my code

here is my code which is running properly but I want to use LoginWithFacebook default button which is provided by facebook.
Is there any image provided by facebook then please give me suggestion.
thankx in advance.....
#import "FacebbokViewController.h"
#import "UserAppAppDelegate.h"
#interface FacebbokViewController ()
#end
#implementation FacebbokViewController
- (id)init
{
self = [super init];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// button which I have used
UIButton *login=[[UIButton alloc]initWithFrame:CGRectMake(100,100, 200,80)];
[login setBackgroundColor:[UIColor blueColor]];
[login setTitle:#"login With facebook" forState:UIControlStateNormal];
[login setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[login addTarget:self action:#selector(loginWithFacebook) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:login];
}
// method which excute on my button click
-(IBAction)loginWithFacebook{
UserAppAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"email", nil];
if(!appDelegate.session.isOpen)
{
// create a fresh session object
appDelegate.session = [[FBSession alloc] init];
[FBSession setActiveSession: appDelegate.session];
[FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
}];
}
else{
NSLog(#"hi");
}
}
- (void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error
{
// If the session was opened successfully
if (!error && state == FBSessionStateOpen){
NSLog(#"Session opened");
[self userData]; // method created to fetch user’s data.
// Show the user the logged-in UI
// do all the things as you have the info you requested from facebook
return;
}
if (state == FBSessionStateClosed || state == FBSessionStateClosedLoginFailed){
// If the session is closed
NSLog(#"Session closed");
// Show the user the logged-out UI
[FBSession.activeSession closeAndClearTokenInformation];
}
// Handle errors
if (error){
NSLog(#"Error");
NSString *alertText;
NSString *alertTitle;
// If the error requires people using an app to make an action outside of the app in order to recover
if ([FBErrorUtility shouldNotifyUserForError:error] == YES){
alertTitle = #"Something went wrong";
alertText = [FBErrorUtility userMessageForError:error];
[self showMessage:alertText withTitle:alertTitle];
} else {
// If the user cancelled login, do nothing
if ([FBErrorUtility errorCategoryForError:error] == FBErrorCategoryUserCancelled) {
NSLog(#"User cancelled login");
// Handle session closures that happen outside of the app
} else if ([FBErrorUtility errorCategoryForError:error] == FBErrorCategoryAuthenticationReopenSession){
alertTitle = #"Session Error";
alertText = #"Your current session is no longer valid. Please log in again.";
[self showMessage:alertText withTitle:alertTitle];
// Here we will handle all other errors with a generic error message.
// We recommend you check our Handling Errors guide for more information
// https://developers.facebook.com/docs/ios/errors/
} else {
//Get more error information from the error
NSDictionary *errorInformation = [[[error.userInfo objectForKey:#"com.facebook.sdk:ParsedJSONResponseKey"] objectForKey:#"body"] objectForKey:#"error"];
// Show the user an error message
alertTitle = #"Something went wrong";
alertText = [NSString stringWithFormat:#"Please retry. \n\n If the problem persists contact us and mention this error code: %#", [errorInformation objectForKey:#"message"]];
[self showMessage:alertText withTitle:alertTitle];
}
}
// Clear this token
[FBSession.activeSession closeAndClearTokenInformation];
}
}
-(void)showMessage:(NSString*)alertMessage withTitle:(NSString*)alertTitle
{
[[[UIAlertView alloc] initWithTitle:alertTitle
message:alertMessage
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] show];
}
-(void)userData
{
// Start the facebook request
[FBRequestConnection startWithGraphPath:#"me" parameters:[NSDictionary dictionaryWithObject:#"id,email" forKey:#"fields"] HTTPMethod:#"GET" completionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *result, NSError *error)
{
//if(!error){
// NSLog(#"result %#",result);
NSString *fbid =result[#"email"];
NSLog(#"result %#",fbid);
//}
}];
}
you can use FBLoginView to have the the functionality as your requirement , you can use like this
FBLoginView *loginView = [[FBLoginView alloc] init];
loginView.frame = YOURFRAME;
[self.view addSubview:loginView];
Take a look at FBLoginView in the Facebook SDK. Official link/tutorial. In the later part of the tutorial, implementing custom views and logging in with API calls is also covered. But note that you would have to design your button on your own in the latter case.

How to share selected text from iphone book app on Facebook

I have iphone book app like all other text when tap and hold a specific words you will see a (copy,define) menu, I want to add another item which is (share) when the user tap it the sharing action sheet will pop up and the user can share that particular words on (Facebook , Twitter , mail or text).
Please help me with details, any help will be appreciated.
social framework:
share Fb or Twitter
- (IBAction)socialSheet:(id)sender {
// create Facebook controller
SLComposeViewController *socialController = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
// add initial text
[socialController setInitialText:#"Hello Facebook!"];
// add an image for you optional
[socialController addImage:[UIImage imageNamed:#"picture.jpg"]];
// add a URL for you optional
[socialController addURL:[NSURL URLWithString:#"http://wpguru.co.uk"]];
// present controller
[self presentViewController:socialController animated:YES completion:nil];
}
Facebook Api
-(void) postWithText: (NSString*) message_text
ImageName: (NSString*) image_name
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_name",
UIImagePNGRepresentation([UIImage imageNamed: image_name]), #"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;
}];
}

Resources