Post to Facebook from iOS App using FacebookSDK - ios

I am using FacebookSDK in one of my applications to Login to the app and Share something. The login is completed and i can now Login to the application using this SDK. Below is the code I am using for login.
-(void)didSelectLoginWithFB
{
if (FBSession.activeSession.isOpen) {
[appDelegate closeSession];
}
else {
[appDelegate openSessionWithAllowLoginUI:YES];
}
if(FBSession.activeSession.accessToken ){
[self performSelector:#selector(FBLoginAction) withObject:nil];
}
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(FBLoginDidFinish:)
name:#"FBLoginDidFinish"
object:appDelegate];
}
-(void)FBLoginDidFinish:(NSNotification *)notification
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[self performSelector:#selector(FBLoginAction) withObject:nil];
}
-(void)FBLoginAction
{
if (FBSession.activeSession.isOpen) {
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *user,
NSError *error) {
if (!error) {
NSDictionary *userInfo = (NSDictionary *)user;
NSLog(#"User dic %#",userInfo);
// fbUserId = user.id;
// NSLog(#"User dic %#",fbUserId);
userMail = [userInfo objectForKey:#"email"];
NSLog(#"User E Mail --- %#", userMail);
loginFlag = 200;
[self getDataFromServer:nil];
}
else{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Facebook Connection Error !!" message:nil delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil ];
[alert show];
}
}];
}
}
Now, I want to post something to the User's facebook wall (timeline). How can I do this using this SDK ? I didn't get any info from developer.facebook.com for this sdk.
Please Help !

I know this is very late, but I hope it'll help..
You can use following code to post on user's wall/timeline-
- (void)postToFacebook{
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
if (appDelegate.session.state != FBSessionStateCreated || !appDelegate.session.isOpen){
// Create a new, logged out session.
NSArray *permissions = [NSArray arrayWithObject:#"publish_actions, publish_stream"];
appDelegate.session = [[FBSession alloc] initWithPermissions:permissions];
// if the session isn't open, let's open it now and present the login UX to the user
[appDelegate.session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
if (appDelegate.session.state!=258 && appDelegate.session.state!=257) {
[self postOpenGraphAction];
}
}];
}else{
if (appDelegate.session.isOpen) {
[self postOpenGraphAction];
}
}
}
- (void)postOpenGraphAction {
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys: #"", #"picture", #"", #"name", #"", #"link", #"", #"caption", #"", #"description", #"Your message to post", #"message", nil];
AppDelegate *appDelegate = (AppDelegate *) [UIApplication sharedApplication].delegate;
[FBSession setActiveSession:appDelegate.session];
[FBRequestConnection startWithGraphPath:#"me/feed" parameters:params HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (error) {
NSLog(#"Error on publishing story: %#", error);
} else {
NSLog(#"Published on wall successfully");
}
}];
}
I have used session object created in my AppDelegate, instead of FBSession activeSession.
You can use as per your code.

Related

Post multiple images using SLComposeViewController on Facebook/ Twitter?

I am an iOS developer and I am currently using SLComposeViewController to share a post on Facebook/Twitter. My issue is that I have to post multiple images in a single post.
I have done this as follows:
SLComposeViewController* mySLComposerSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
[mySLComposerSheet setInitialText:textTobeShared];
mySLComposerSheet addURL:[NSURL URLWithString:#"http://click-labs.com/"]];
for(int count=0;count<imageArray.count;count++)
if([mySLComposerSheet addImage:[UIImage imageWithData:[imageArray objectAtIndex:count]]])
In the above code, imageArray is the array of images that I want to post.
When I am doing this on Facebook, all the images are posted as a separate post.
While in case of Twitter, addImage method returns true only for the first images while in case of other images it returns false. So only one image is posted.
So I want to know how to achieve my goal and is it possible to post multiple images in a single tweet.
I think you need to create an album first.
Here's a link to the facebook album API documentation.
- (void)shareToFacebook {
if (FBSession.activeSession.isOpen) {
NSLog(#"SESSION IS OPEN");
[self createFacebookAlbum];
} else {
NSLog(#"SESSION IS NOT OPEN");
NSArray* permissions = [NSArray arrayWithObject:#"email"];
[FBSession openActiveSessionWithReadPermissions:permissions allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
if (error) {
/* handle failure */
NSLog(#"error:%#, %#", error, [error localizedDescription]);
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"There was a problem with your Facebook permissions." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
else if (state == FBSessionStateClosed || state == FBSessionStateClosedLoginFailed ) {
[FBSession.activeSession closeAndClearTokenInformation];
}
else if (state == FBSessionStateOpenTokenExtended || state == FBSessionStateOpen) {
if(!self.presentedFacebookSheet) {
[self performSelector:#selector(reauthorizeAndContinuePostToFacebook) withObject:nil afterDelay:0.5];
self.presentedFacebookSheet = YES;
}
}
}];
}
}
- (void)reauthorizeAndContinuePostToFacebook {
NSArray *permissions = [NSArray arrayWithObjects:#"publish_actions", nil];
[[FBSession activeSession] requestNewPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends completionHandler:^(FBSession *session, NSError *error) {
[self shareToFacebook];
}];
}
- (void)createFacebookAlbum {
NSMutableDictionary* parameters = [NSMutableDictionary dictionary];
[parameters setObject:#"Test name" forKey:#"name"];
[parameters setObject:#"Test message" forKey:#"message"];
FBRequest* request = [FBRequest requestWithGraphPath:#"me/albums" parameters:parameters HTTPMethod:#"POST"];
NSLog(#"creating facebook album");
FBRequestConnection *connection = [[FBRequestConnection alloc] init];
[connection addRequest:request
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSString* albumId = [result objectForKey:#"id"];
NSLog(#"OK %#", albumId);
}
else {
NSLog(#"Error: %#",error.userInfo);
}
}];
[connection start];
}
- (void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error {
switch (state) {
case FBSessionStateOpen:
{
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *user,
NSError *error) {
if (error) {
//error
}
else {
NSLog(#"User session found");
}
}];
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
break;
}
}

Hyper link in iOS Facebook

I need to share the link to Facebook. when user press that link that should take user to another page.
I tried the following code..but it only just share string..it doest not act like hyperlink..
-(void)fbShare
{
[hud show:YES];
NSString *title=[NSString stringWithFormat:#"www.google.com"];
MAAppDelegate *appdelegate = (MAAppDelegate *)[[UIApplication sharedApplication] delegate] ;
if (!appdelegate.session) {
appdelegate.session = [[FBSession alloc]initWithPermissions:[NSArray arrayWithObjects:#"publish_stream",nil]];
}
if (![appdelegate.session isOpen]) {
[appdelegate.session openWithCompletionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if (!error) {
[self Share:title];
}else {
NSLog(#"facebook errror %#",error.description);
[hud hide:YES];
}
}];
} else {
[self Share:title];
}
}
-(void)Share:(NSString *)text
{
MAAppDelegate *appdelegate = (MAAppDelegate *)[[UIApplication sharedApplication] delegate];
UIImage *image = [UIImage imageNamed:#"bath3.png"];
[FBSession setActiveSession:appdelegate.session];
NSData *dataImage=UIImageJPEGRepresentation(image,1.0);
NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithObjectsAndKeys:text, #"name", dataImage, #"picture", #"image/png", #"content_type", nil];
FBRequest *request=[FBRequest requestWithGraphPath:#"me/photos" parameters:parameters HTTPMethod:#"POST"];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(!error) {
NSLog(#"Success");
[hud hide:YES];
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Audalize POC" message:#"Shared Successfully" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
} else {
[hud hide:YES];
NSLog(#"failed %#",error.localizedDescription);
}
}];
}
Read this : https://developers.facebook.com/docs/ios/share/
You need to use " link" key for sharing links to facebook.
Ex :
[NSMutableDictionary dictionaryWithObjectsAndKeys:text,#"link", // < ----
dataImage,#"picture",
#"image/png",#"content_type"
,nil];

FBSession: an attempt was made reauthorize permissions on an unopened session in ios

Hi I am using facebook SDK 3.8 in my project. and using HelloFaceBookSample Code in my app but in my app i have no login button of facebook. I have implemented login flow of facebook and after login i have post on facebook. Now Post Status working fine but when i post image on facebook it give me error of
an attempt was made reauthorize permissions on an unopened session in ios
Code :
-(void) clickButtonFacebookUsingSDK
{
if (!appdelegate.session.isOpen)
{
appdelegate.session = [[FBSession alloc] init];
[appdelegate.session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
if(appdelegate.session.isOpen)
{
NSLog(#"calling postdata when session is not open******");
[self postData];
}
}];
}
else
{
NSLog(#"calling postdata when session is open******");
[self postData];
}
}
-(void) postData
{
[self showingActivityIndicator];
UIImage *img = [UIImage imageNamed:#"abc.jpg"];
[self performPublishAction:^{
FBRequestConnection *connection = [[FBRequestConnection alloc] init];
connection.errorBehavior = FBRequestConnectionErrorBehaviorReconnectSession
| FBRequestConnectionErrorBehaviorAlertUser
| FBRequestConnectionErrorBehaviorRetry;
FBRequest *req = [FBRequest requestForUploadPhoto:img];
[req.parameters addEntriesFromDictionary:[NSMutableDictionary dictionaryWithObjectsAndKeys:message3, #"message", nil]];
[connection addRequest:req
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
// [self showAlert:#"Photo Post" result:result error:error];
[self showAlert:#"Photo Post" result:result resulterror:error];
if (FBSession.activeSession.isOpen) {
}
}];
[connection start];
}];
}
- (void) performPublishAction:(void (^)(void)) action {
// we defer request for permission to post to the moment of post, then we check for the permission
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound)
{
// if we don't already have the permission, then we request it now
[FBSession.activeSession requestNewPublishPermissions:#[#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error)
{
if (!error) {
action();
} else if (error.fberrorCategory != FBErrorCategoryUserCancelled){
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Permission denied"
message:#"Unable to get permission to post"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}];
} else {
action();
}
}
// UIAlertView helper for post buttons
- (void)showAlert:(NSString *)message result:(id)result resulterror:(NSError *)error
{
NSString *alertMsg;
NSString *alertTitle;
if (error)
{
alertTitle = #"Error";
// Since we use FBRequestConnectionErrorBehaviorAlertUser,
// we do not need to surface our own alert view if there is an
// an fberrorUserMessage unless the session is closed.
if (FBSession.activeSession.isOpen) {
alertTitle = #"Error";
} else {
// Otherwise, use a general "connection problem" message.
alertMsg = #"Operation failed due to a connection problem, retry later.";
}
}
else
{
NSDictionary *resultDict = (NSDictionary *)result;
alertMsg = [NSString stringWithFormat:#"Successfully posted '%#'.", message];
NSString *postId = [resultDict valueForKey:#"id"];
if (!postId) {
postId = [resultDict valueForKey:#"postId"];
}
if (postId) {
alertMsg = [NSString stringWithFormat:#"%#\nPost ID: %#", alertMsg, postId];
}
alertTitle = #"Success";
}
if (alertTitle) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle
message:alertMsg
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[self dismissActivityIndicator];
}
}
it gives me error in performPublishAction method.
can anyone tell me what is the problem . i have a lot of search and also found many solution but no one work. Please help. Thanks in advance.
I think that you have to set to FBSession what is its active session :
FBSession *session = [[FBSession alloc] init];
[FBSession setActiveSession:session];

adding a Post To Facebook Timeline from iOS APP

HI Im trying to enable a IBAction to post on an user's timeline while they have an active section. I am getting an error message stating; Implicit declaration of function "x" is invalid C99. I been reading posts about the issue but no luck and honestly I am not sure if I am doing this right at all. I updated the permissions on my fb app and got the object code from the Graph API Explorer but I dont know if Im implementing it right on my code.
Here is my post method:
-(void) aPost
{
NSMutableDictionary<FBGraphObject> *object =
[FBGraphObject openGraphObjectForPostWithType:#"website"
title:#"CR Taxi APP"
image:#"http://a4.mzstatic.com/us/r1000/047/Purple4/v4/05/cc/f2/05ccf23f-a409-1e73-a649-a5e6afc4e6eb/mzl.llffzfbp.175x175-75.jpg"
url:#"https://itunes.apple.com/cr/app/cr-taxi/id674226640?mt=8"
description:#"La nueva aplicaciĆ³n para llamar taxis!"];;
[FBRequestConnection startForPostWithGraphPath:#"{id_from_create_call}"
graphObject:object
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
// handle the result
}];
}
and this is my action method
- (IBAction)publishAction:(id)sender {
if ([FBSession.activeSession.permissions
indexOfObject:#"publish_actions"] == NSNotFound) {
NSArray *writepermissions = [[NSArray alloc] initWithObjects:
#"publish_stream",
#"publish_actions",
nil];
[[FBSession activeSession]requestNewPublishPermissions:writepermissions defaultAudience:FBSessionDefaultAudienceFriends completionHandler:^(FBSession *aSession, NSError *error){
if (error) {
NSLog(#"Error on public permissions: %#", error);
}
else {
**not on the code //( error on this one) aPost(aSession, error);
}
}];
}
else {
// If permissions present, publish the story
**not on the code //(not an error on this one) aPost(FBSession.activeSession, nil);
}
}
Please help!
Thank you!
I'd guess the compiler error is actually "Implicit declaration of function 'aPost' is invalid C99", although the formatting of your action method code is wonky as written. The compiler is only going to produce that error message the first time it encounters the function call to aPost.
aPost is written as a method that has no return and takes no arguments. You are trying to call it as a C function, passing it two arguments, which the compiler interprets as an entirely new function. As aPost is written with all the hard-coded strings, you probably just want to change the calls to aPost(arg1, arg2); to [self aPost]; (provided aPost and publishAction are in the same class).
Try this: might helps you
//Write This Line in your ViewController.h File
#property (strong, nonatomic) NSMutableDictionary *postParams;
//in View Controller.m File
- (void)viewDidLoad
{
self.postParams =
[[NSMutableDictionary alloc] initWithObjectsAndKeys:
[UIImage imageNamed:#"Default.png"], #"picture",
#"Facebook SDK for iOS", #"name",
#"build apps.", #"caption",
#"testing for my app.", #"description",
nil];
[self.postParams setObject:#"hgshsghhgsls" forKey:#"message"];
}
- (IBAction)SharePressed:(id)sender {
#try {
[self openSession];
NSArray *permissions =[NSArray arrayWithObjects:#"publish_actions",#"publish_stream",#"manage_friendlists",#"read_stream", nil];
[[FBSession activeSession] reauthorizeWithPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
/* handle success + failure in block */
if (![session isOpen]) {
[self openSession];
}
}];
[FBRequestConnection startWithGraphPath:#"me/feed" parameters:self.postParams HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,id result,NSError *error) {
NSString *alertText;
if (error) {
alertText = [NSString stringWithFormat:#"error: domain = %#, code = %d, des = %#",error.domain, error.code,error.description];
}
else
{
alertText=#"Uploaded Successfully";
[self ResetAllcontent];
}
// Show the result in an alert
[[[UIAlertView alloc] initWithTitle:#"Result" message:alertText delegate:self cancelButtonTitle:#"OK!"
otherButtonTitles:nil]show];
}];
}
#catch (NSException *exception) {
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Please Login" message:#"For Sharing on facbook please login with facbook" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:nil, nil];
[alert show];
}
#finally {
}
}
- (void)openSession
{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
[FBSession openActiveSessionWithReadPermissions:nil
allowLoginUI:YES
completionHandler:
^(FBSession *session,
FBSessionState state, NSError *error) {
[appDelegate sessionStateChanged:session state:state error:error];
}];
ACAccountStore *accountStore;
ACAccountType *accountTypeFB;
if ((accountStore = [[ACAccountStore alloc] init]) &&
(accountTypeFB = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook] ) ){
NSArray *fbAccounts = [accountStore accountsWithAccountType:accountTypeFB];
id account;
if (fbAccounts && [fbAccounts count] > 0 &&
(account = [fbAccounts objectAtIndex:0])){
[accountStore renewCredentialsForAccount:account completion:^(ACAccountCredentialRenewResult renewResult, NSError *error) {
//we don't actually need to inspect renewResult or error.
if (error){
}
}];
}
}
}
}
//=====in your plist file do
URLTypes=>Item 0=> URL Schemes =>Item 0=>fbyourfacebookId
FacebookAppID-your facebookID
And yes dont forget to create facebook id at developer.facebook.com
and also give permissions as your need
- (IBAction)shareViaFacebook:(id)sender {
if (FBSession.activeSession.isOpen) {
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:#"%#. Join on Linute.",self.userNameLabel.text], #"name",
//#"Build great social apps and get more installs.", #"caption",
locationString, #"description",
//#"http://www.linute.com/", #"link",
eventPicString, #"picture",//imageURL
nil];
// Make the request
[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 {
// An error occurred, we need to handle the error
// See: https://developers.facebook.com/docs/ios/errors
NSLog(#"%#", error.description);
}
}];
}else{
FBSession *session = [[FBSession alloc] initWithPermissions:#[#"public_profile", #"email",#"user_friends",#"publish_actions"]];
[FBSession setActiveSession:session];
[session openWithBehavior:FBSessionLoginBehaviorWithFallbackToWebView completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if (FBSession.activeSession.isOpen) {
[self shareViaFacebook:nil];
}else{
[self shareViaFacebook:nil];
}
}];
}

Dismiss facebook window programmatically

My requirement is to close Facebook window in certain conditions via code.
I am using Facebook iOS SDK 3.5.1.
Is there any way to get visible (Facebook) screen on running app or to dismiss Facebook screen programmatically?
I am using facebook for 2 scenarios-
for login
for sending app request.
Code for both are below-
1. For login:
AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
if (appDelegate.session.state != FBSessionStateCreated || !appDelegate.session.isOpen) {
// Create a new, logged out session.
NSArray *permissions = [NSArray arrayWithObjects:#"publish_stream",#"user_birthday",#"user_photos", #"email", #"user_location", #"user_hometown", nil];
appDelegate.session = [[FBSession alloc] initWithPermissions:permissions];
}
[appDelegate.session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
if (appDelegate.session.state!=258 && appDelegate.session.state!=257) {
[self accessTokenFound:appDelegate.session.accessToken];
}
}];
2. For app requests
NSMutableDictionary* params = [NSMutableDictionary dictionary];
AppDelegate* appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
[params setObject:friendID forKey:#"to"];
// Display the requests dialog
[FBWebDialogs
presentRequestsDialogModallyWithSession:appDelegate.session
message:message
title:nil
parameters:params
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
NSLog(#"Error sending request.");
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
NSLog(#"User canceled request.");
} else {
NSDictionary *urlParams = [self parseURLParams:[resultURL query]];
if (![urlParams valueForKey:#"request"]) {
NSLog(#"User canceled request.");
} else {
NSString *requestID = [urlParams valueForKey:#"request"];
[self requestSentSuccessfully];
}
}
}
}];

Resources