adding a Post To Facebook Timeline from iOS APP - ios

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];
}
}];
}

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;
}
}

Can't get Facebook friends with FBFriendPicker in iOS

I want to get Facebook friends in my project. I have tried the FBFriendPicker Method, but I can't get the friends. It shows empty list to me.
Here is my code.
- (IBAction)pickFriendsButtonClick:(id)sender {
if (!FBSession.activeSession.isOpen) {
[FBSession openActiveSessionWithReadPermissions:#[#"public_profile", #"user_friends"]
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
} else if (session.isOpen) {
[self pickFriendsButtonClick:sender];
}
}];
return;
}
if (self.friendPickerController == nil) {
// Create friend picker, and get data loaded into it.
self.friendPickerController = [[FBFriendPickerViewController alloc] init];
self.friendPickerController.title = #"Pick Friends";
self.friendPickerController.delegate = self;
}
[self.friendPickerController loadData];
[self.friendPickerController clearSelection];
[self presentModalViewController:self.friendPickerController animated:YES];
}
Try This...
-(IBAction)btnFacebookClick:(id)sender
{
NSArray *permissions = [[NSArray alloc] initWithObjects: #"user_about_me,user_birthday,user_hometown,user_location,email",#"read_mailbox",#"read_stream",nil];
[FBSession openActiveSessionWithReadPermissions:permissions allowLoginUI:YES completionHandler:^(FBSession *session,FBSessionState status,NSError *error)
{
if(error)
{
NSLog(#"session error %#",error);
}
else if(FB_ISSESSIONOPENWITHSTATE(status))
{
[self getFriendList];
}
}];
}
-(void)getFriendList
{
FBRequest *friendsRequest=[FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler:^(FBRequestConnection *connection,NSDictionary* result,NSError *error)
{
friendsArr = [result objectForKey:#"data"];
NSLog(#"friends description :%#",[friendsArr description]);
}];
}
Try this code for get facebook friends....
FBRequest* friendsRequest = [FBRequest requestForMyFriends];
friendsRequest.session = FBSession.activeSession;
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,
NSDictionary* result,
NSError *error) {
NSArray* friends = [result objectForKey:#"data"];
NSLog(#"Found: %lu friends", (unsigned long)friends.count);
for (NSDictionary<FBGraphUser>* friend in friends)
{
NSLog(#"I have a friend named %# ", friend.name);
}
}];
Please try below code :
[FBSession openActiveSessionWithReadPermissions:#[#"email"]
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
if (error) {
// Handle errors
[self handleAuthError:error];
}
else
{
// Check for publish permissions
FBRequest *req = [FBRequest requestForMyFriends];
[req startWithCompletionHandler:^(FBRequestConnection *connection,NSDictionary *result,NSError *error){
NSLog(#"Result:- %#",[result objectForKey:#"data"]);
}];
}
}];
With the new API version v2.0, you cannot get the complete list of friends just with user_friends. Your picker must be using /me/friends which will give you the list of friends using that app. So in your case none of your friends be using this app and that's why you are getting a blank response.
To get the complete list of friends you should use /me/taggable_friends API. But note that this permission needs to be reviewed first by facebook before you go live. See this answer for more info for using this permission.

Facebook SDK and iOS

I am trying to post a status using Facebook SDK.
Some of the users are already signed in using Facebook.
So I have this code:
if (FBSession.activeSession.isOpen) {
NSLog(#"Already Open%#",[[FBSession activeSession] accessTokenData].accessToken);
// NSString *tok = [[FBSession activeSession] accessTokenData].accessToken;
NSArray *permissions = [NSArray arrayWithObjects:#"publish_actions", nil];
[[FBSession activeSession] requestNewPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session,NSError *error) {
if(!error){
NSLog(#"Publish Permission Granted");
}
else
{
NSLog(#"Publish to get Read Permission");
} }];
//Remove indicator
[_activityView removeFromSuperview];
} else {
// OPEN Session!
[FBSession openActiveSessionWithReadPermissions:nil
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.
NSLog(#"----%#",[session accessTokenData].accessToken);
//NSString *tok = [session accessTokenData].accessToken;
NSArray *permissions = [NSArray arrayWithObjects:#"publish_actions", nil];
[[FBSession activeSession] requestNewPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session,NSError *error) {
if(!error){
NSLog(#"Publish Permission Granted");
}
else
{
NSLog(#"Publish to get Read Permission");
} }];
[_activityView removeFromSuperview];
// [self promptUserWithAccountName]; // a custom method - see below:
}
}];
}
So lets focus on the first part which is suppose that the user has open session( the second one is just opening a new one in case that is no session available). How I am going to post a status with a url and a picture after granting publish permissions? Facebook examples are not helping at all. I found some other examples but most of them are outdated.
I managed to post a simple post with:
FBRequest *postRequest = [FBRequest requestForPostStatusUpdate:#"hi" ];
[postRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
// TODO: Check for success / failure here
}];
after granding publish permission. I want something similar with url description imgurl and title.
This is how I did it, in my ibaction method:
Sharing Image:
UIImage *img = myImage;
FBLoginView *loginview = [[FBLoginView alloc] init];
loginview.delegate = self;
[self performPublishAction:^{
[FBRequestConnection startForUploadPhoto:img
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
[self showAlert:#"Photo Post" result:result error:error];
}];
}];
Sharing URL:
NSURL *urlToShare = [NSURL URLWithString:#"http://developers.facebook.com/ios"];
FBAppCall *appCall = [FBDialogs presentShareDialogWithLink:urlToShare
name:#"Hello Facebook"
caption:nil
description:#"The 'Hello Facebook' sample application showcases simple Facebook integration."
picture:nil
clientState:nil
handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
if (error) {
NSLog(#"Error: %#", error.description);
} else {
NSLog(#"Success!");
}
}];
Add these as well:
- (void) performPublishAction:(void (^)(void)) action
{
if([[FBSession activeSession]isOpen])
{
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();
}
//For this example, ignore errors (such as if user cancels).
}];
} else {
action();
}
}
else
{
[FBSession openActiveSessionWithPublishPermissions:[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if (!error && status == FBSessionStateOpen) {
}else{
NSLog(#"Session error");
[self fbResync];
[NSThread sleepForTimeInterval:0.5]; //half a second
[FBSession openActiveSessionWithPublishPermissions:[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState status, NSError *error){
}];
}
}];
}
}
- (void)loginViewShowingLoggedInUser:(FBLoginView *)loginView
{
}
- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView
user:(id<FBGraphUser>)user
{
self.loggedInUser = user;
}
- (void)loginViewShowingLoggedOutUser:(FBLoginView *)loginView
{
self.loggedInUser = nil;
}
-(void)fbResync
{
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){
}
}];
}
}
}
Hope this helps... Look at HelloFacebookSample in Facebook SDK Samples.
Try this:
[self performPublishAction:^{
NSString *message = [NSString stringWithFormat:#"Updating status for %# at %#", self.loggedInUser.first_name, [NSDate date]];
[FBRequestConnection startForPostStatusUpdate:message
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
[self showAlert:message result:result error:error];
self.buttonPostStatus.enabled = YES;
}];
self.buttonPostStatus.enabled = NO;
}];

Facebook iOS SDK 3.1 | "You have already authorized YOUR_APP" appears every time user tries to login

I'm currently trying to implement the Facebook-Login-Flow with iOS Facebook SDK 3.1.
But there is a little Problem with it. Every time the user logs in with facebook the webview will open up and says
"You have already authorized YOUR_APP.."
The code I wrote based on the following example: click here
Now my question is, how can I avoid this behaviour and what I am doing wrong?
Please see this code ,it may help
postParams=
[#{
#"link" :link,
#"picture" :picture link , //[NSString stringWithFormat:#"%#%#",KBaseImageUrl,#"/assets/img/logo-small.jpg"],
#"name" : #“name”,
#"caption" : caption title,
#"description" :discription
} mutableCopy];
title=[[arrayEventInfo valueForKey:#"info"] valueForKey:#"eventname"];
if ([[FBSession activeSession]isOpen])
{
if ([[[FBSession activeSession]permissions]indexOfObject:#"publish_actions"] == NSNotFound)
{
[[FBSession activeSession] requestNewPublishPermissions:[NSArray arrayWithObject:#"publish_action"] defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session,NSError *error){
// If permissions granted, publish the story
[FBRequestConnection
startWithGraphPath:#"me/feed"
parameters:postParams
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 = #"Posted successfully on your wall.";//[NSString stringWithFormat:
//#"Posted action, id: %#",
// result[#"id"]];
}
//Show the result in an alert
[[[UIAlertView alloc] initWithTitle:title
message:alertText
delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil]show];
[FBSession.activeSession closeAndClearTokenInformation];
[FBSession.activeSession close];
}];
UIActivityIndicatorView *activityView=(UIActivityIndicatorView*)[self.view viewWithTag:111];
if(activityView)
{
[activityView removeFromSuperview];
}
[self.view setUserInteractionEnabled:YES];
[self.navigationController.navigationBar setUserInteractionEnabled:YES];
}];
}else
{
// If permissions granted, publish the story
[FBRequestConnection
startWithGraphPath:#"me/feed"
parameters:postParams
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 = #"Posted successfully on your wall.";//[NSString stringWithFormat:
//#"Posted action, id: %#",
// result[#"id"]];
}
//Show the result in an alert
[[[UIAlertView alloc] initWithTitle:title
message:alertText
delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil]show];
[FBSession.activeSession closeAndClearTokenInformation];
[FBSession.activeSession close];
}];
}
}
else
{
[FBSession openActiveSessionWithPublishPermissions:[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceOnlyMe
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if (!error && status == FBSessionStateOpen) {
if (!error)
{
// If permissions granted, publish the story
[FBRequestConnection
startWithGraphPath:#"me/feed"
parameters:postParams
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 = #"Posted successfully on your wall.";//[NSString stringWithFormat:
//#"Posted action, id: %#",
// result[#"id"]];
}
//Show the result in an alert
[[[UIAlertView alloc] initWithTitle:title
message:alertText
delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil]show];
[FBSession.activeSession closeAndClearTokenInformation];
[FBSession.activeSession close];
}];
}
}else{
NSLog(#"%#",[error description]);
UIActivityIndicatorView *activityView=(UIActivityIndicatorView*)[self.view viewWithTag:111];
if(activityView)
{
[activityView removeFromSuperview];
}
[self.view setUserInteractionEnabled:YES];
[self.navigationController.navigationBar setUserInteractionEnabled:YES];
}
}];
}
If you are testing the code in dev then the first time you log in it will store that session on Facebook.
So, you try to test it again but it is already authorized.
If you want to test the login process again then go to Facebook and de-authorize your app (it will be in your list of apps).
Then you can log in again on the device.

Publish picture with caption on application album whether it exists or not using Facebook SDK 3.1 for iOS

Using toblerpwn answer i manage to publish a picture to the application album as i wanted to.
But this works only when the application album has already been created (because i need to specify the album id).
In the other hand the requestForUploadPhoto convenience method creates the application album if it doesn't exists and publishes the picture.
So could someone help me figure out how to merge this two beheviours?
Thanks to #deepak-lakshmanan i manage to solve my problem.
The idea is to publish to the application album using /USER_ID/photos insted of /ALBUM_ID/photos; this way the album is automatically created if it doesn't exist.
So the steps to follow are:
get the publish permission
then retrieve the user id using /me
finally publish the picture to the application album with /USER_ID/photos
Here is my code in case someone struggles with this, am using Facebook SDK 3.1 for iOS:
- (void)sendRequestFacebookPublishPermission {
NSArray *permissions = [[NSArray alloc] initWithObjects:#"publish_stream", nil];
if(!FBSession.activeSession.isOpen ) {
[FBSession openActiveSessionWithPublishPermissions:permissions
defaultAudience:FBSessionDefaultAudienceFriends
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
[self requestFacebookPublishPermissionCompleted:session status:status error:error];
}];
} else if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound) {
[FBSession.activeSession reauthorizeWithPublishPermissions:permissions
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
[self requestFacebookPublishPermissionCompleted:session status:FBSessionStateOpen error:error];
}];
} else {
[self sendRequesFacebooktUserInfo];
}
}
- (void)requestFacebookPublishPermissionCompleted:(FBSession *)session
status:(FBSessionState)status
error:(NSError *)error {
if (error) {
DLog(#"%#", error.localizedDescription);
} else {
[self sendRequesFacebooktUserInfo];
}
}
-(void)sendRequesFacebooktUserInfo {
FBRequestConnection *newConnection = [[FBRequestConnection alloc] init];
// output the results of the request
FBRequestHandler handler = ^(FBRequestConnection *connection, id result, NSError *error) {
[self requestFacebookUserInfoCompleted:connection result:result error:error];
};
// create the request object, using the fbid as the graph path
FBRequest *request = [[FBRequest alloc] initWithSession:FBSession.activeSession graphPath:#"me"];
// add the request to the connection object
[newConnection addRequest:request completionHandler:handler];
// if there's an outstanding connection, just cancel
[self.requestConnection cancel];
// keep track of our connection, and start it
self.requestConnection = newConnection;
[newConnection start];
}
- (void)requestFacebookUserInfoCompleted:(FBRequestConnection *)connection
result:(id)result
error:(NSError *)error {
// not the completion we were looking for...
if (self.requestConnection && connection != self.requestConnection) {
return;
}
// clean this up, for posterity
self.requestConnection = nil;
if (error) {
DLog(#"%#", error.localizedDescription);
} else {
FBGraphObject *dictionary = (FBGraphObject *)result;
NSString* userId = (NSString *)[dictionary objectForKey:#"id"];
[self sendRequestFacebookPublishOnAlbum:userId];
}
}
- (void)sendRequestFacebookPublishOnAlbum:(NSString*)fbId {
UIImage *imageToPost = /* get the image you need*/ ;
/*
//--- Facebook SDK convenience method : requestForUploadPhoto won't let me post image description ---//
FBRequestConnection *newConnection = [FBRequestConnection startForUploadPhoto:screenshot completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
[self requestPostCardOnFacebookCompleted:connection result:result error:error];
}];
// if there's an outstanding connection, just cancel
[self.requestConnection cancel];
// keep track of our connection, and start it
self.requestConnection = newConnection;
//-----------------------------------------------------------------------------------------------------//
*/
//--- http://stackoverflow.com/questions/12486852/facebook-ios-sdk-cannot-specify-an-album-using-fbrequests-requestforuploadphot ---//
NSString *messagePublie = laCarte.message;
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:
screenshot, #"picture",
messagePublie , #"name",
nil] ;
FBRequestConnection *newConnection = [[FBRequestConnection alloc] init];
FBRequestHandler handler = ^(FBRequestConnection *connection, id result, NSError *error) {
[self requestFacebookPublishOnAlbumCompleted:connection result:result error:error];
};
NSString *graphPath = [NSString stringWithFormat:#"%#/photos",fbId];
FBRequest *request = [[FBRequest alloc] initWithSession:FBSession.activeSession graphPath:graphPath parameters:parameters HTTPMethod:#"POST"];
[newConnection addRequest:request completionHandler:handler];
// if there's an outstanding connection, just cancel
[self.requestConnection cancel];
// keep track of our connection, and start it
self.requestConnection = newConnection;
[newConnection start];
}
- (void)requestFacebookPublishOnAlbumCompleted:(FBRequestConnection *)connection result:(id)result error:(NSError *)error {
if (self.requestConnection && connection != self.requestConnection) {
return;
}
// clean this up, for posterity
self.requestConnection = nil;
if (error) {
DLog(#"%#", error.localizedDescription);
} else {
DLog(#"%#", "Done");
}
}

Resources