Facebook sdk post on wall on iPhone app - iphone

I have a problem with implementing Facebook posting on wall in my iPhone application.
I installed SDK and linked framework
login is working fine. here's the code:
-(IBAction)loginButtonPressed:(id)sender
{
NSLog(#"loginButtonPressed: called");
AppDelegate *appdel=[[UIApplication sharedApplication] delegate];
appdel.facebookSession=[[FBSession alloc] init];
[appdel.facebookSession openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error)
{
//
}];
}
But I have a problem with posting message on user's wall. Here's the code:
-(IBAction)likeButtonPressed:(id)sender
{
NSLog(#"likeButtonPressed: called");
// Post a status update to the user's feedm via the Graph API, and display an alert view
// with the results or an error.
NSString *message = #"test message";
NSDictionary *params = [NSDictionary dictionaryWithObject:message forKey:#"message"];
// use the "startWith" helper static on FBRequest to both create and start a request, with
// a specified completion handler.
[FBRequest startWithGraphPath:#"me/feed"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
[self showAlert:message result:result error:error];
}];
}
Help me please. What's wrong with my code? Or should I add some permissions to login request?

this code worked for me.
First we must
#import <FBiOSSDK/FacebookSDK.h>
then
#property (strong, nonatomic) FBRequestConnection *requestConnection;
and of course do not forget to synthesize:
#synthesize requestConnection;
the code itself:
-(IBAction)likeButtonPressed:(id)sender
{
NSLog(#"likeButtonPressed: called");
// FBSample logic
// Check to see whether we have already opened a session.
if (FBSession.activeSession.isOpen)
{
// login is integrated with the send button -- so if open, we send
[self postOnWall];
}
else
{
[FBSession sessionOpenWithPermissions:[NSArray arrayWithObjects:#"publish_stream", nil]
completionHandler:
^(FBSession *session,
FBSessionState status,
NSError *error)
{
// if login fails for any reason, we alert
if (error)
{
NSLog(#" login failed");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
// if otherwise we check to see if the session is open, an alternative to
// to the FB_ISSESSIONOPENWITHSTATE helper-macro would be to check the isOpen
// property of the session object; the macros are useful, however, for more
// detailed state checking for FBSession objects
}
else if (FB_ISSESSIONOPENWITHSTATE(status))
{
NSLog(#" sending post on wall request...");
// send our requests if we successfully logged in
[self postOnWall];
}
}];
};
}
- (void)postOnWall
{
NSNumber *testMessageIndex=[[NSNumber alloc] init];
if ([[NSUserDefaults standardUserDefaults] objectForKey:#"testMessageIndex"]==nil)
{
testMessageIndex=[NSNumber numberWithInt:100];
}
else
{
testMessageIndex=[[NSUserDefaults standardUserDefaults] objectForKey:#"testMessageIndex"];
};
testMessageIndex=[NSNumber numberWithInt:[testMessageIndex intValue]+1];
[[NSUserDefaults standardUserDefaults] setObject:testMessageIndex forKey:#"testMessageIndex"];
[[NSUserDefaults standardUserDefaults] synchronize];
// create the connection object
FBRequestConnection *newConnection = [[FBRequestConnection alloc] init];
// create a handler block to handle the results of the request for fbid's profile
FBRequestHandler handler =
^(FBRequestConnection *connection, id result, NSError *error) {
// output the results of the request
[self requestCompleted:connection forFbID:#"me" result:result error:error];
};
// create the request object, using the fbid as the graph path
// as an alternative the request* static methods of the FBRequest class could
// be used to fetch common requests, such as /me and /me/friends
NSString *messageString=[NSString stringWithFormat:#"wk test message %i", [testMessageIndex intValue]];
FBRequest *request=[[FBRequest alloc] initWithSession:FBSession.activeSession graphPath:#"me/feed" parameters:[NSDictionary dictionaryWithObject:messageString forKey:#"message"] HTTPMethod:#"POST"];
// add the request to the connection object, if more than one request is added
// the connection object will compose the requests as a batch request; whether or
// not the request is a batch or a singleton, the handler behavior is the same,
// allowing the application to be dynamic in regards to whether a single or multiple
// requests are occuring
[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];
}
// FBSample logic
// Report any results. Invoked once for each request we make.
- (void)requestCompleted:(FBRequestConnection *)connection
forFbID:fbID
result:(id)result
error:(NSError *)error
{
NSLog(#"request completed");
// not the completion we were looking for...
if (self.requestConnection &&
connection != self.requestConnection)
{
NSLog(#" not the completion we are looking for");
return;
}
// clean this up, for posterity
self.requestConnection = nil;
if (error)
{
NSLog(#" error");
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"error" message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
// error contains details about why the request failed
[alert show];
}
else
{
NSLog(#" ok");
};
}

try this code
NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray* facebookCookies = [cookies cookiesForURL:
[NSURL URLWithString:#"http://login.facebook.com"]];
for (NSHTTPCookie* cookie in facebookCookies) {
[cookies deleteCookie:cookie];
}
NSString *FBBody = [NSString stringWithFormat:#"your message you want to post"];
UIImage *img=[UIImage imageNamed:[NSString stringWithFormat:image naemif you want to post]];
FBFeedPost *post = [[FBFeedPost alloc] initWithPhoto:img name:FBBody];
[post publishPostWithDelegate:self];
[[UIAppDelegate indicator] startAnimating];
IFNNotificationDisplay *display = [[IFNNotificationDisplay alloc] init];
display.type = NotificationDisplayTypeLoading;
display.tag = NOTIFICATION_DISPLAY_TAG;

you should set Permissions:"status_update".
like this :
FBLoginView *loginview = [[FBLoginView alloc] initWithPermissions:[NSArray arrayWithObject:#"status_update"]];
or
FBSession *fbSession = [[FBSession alloc] initWithPermissions:[NSArray arrayWithObject:#"status_update"]];

Related

Fetching user details from Facebook in iOS

I'm new to iPhone development. I'm doing an App where the user has 2 login through Facebook, once he submits his credentials and clicks on Sign In button, I have to fetch details like First name, email and gender from Facebook and after fetching the user has to be directed to the Registration page of the app with the details filled and i need this app to be compatible for iPhone 4,4s and 5.
I tried doing this using the Facebook Graph API but couldn't get it, so anyone can help me out.
Thanks in Advance.
You can do this by using following code :
[FBSession openActiveSessionWithReadPermissions:#[#"email",#"user_location",#"user_birthday",#"user_hometown"]
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
switch (state) {
case FBSessionStateOpen:
[[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (error) {
NSLog(#"error:%#",error);
}
else
{
// retrive user's details at here as shown below
NSLog(#"FB user first name:%#",user.first_name);
NSLog(#"FB user last name:%#",user.last_name);
NSLog(#"FB user birthday:%#",user.birthday);
NSLog(#"FB user location:%#",user.location);
NSLog(#"FB user username:%#",user.username);
NSLog(#"FB user gender:%#",[user objectForKey:#"gender"]);
NSLog(#"email id:%#",[user objectForKey:#"email"]);
NSLog(#"location:%#", [NSString stringWithFormat:#"Location: %#\n\n",
user.location[#"name"]]);
}
}];
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
break;
}
} ];
and don't forgot to import FacebookSDK/FacebookSDK.h in your code.
EDIT : Update for Facebook SDK v4 (23 April,2015)
Now, Faceboook have released new SDK with major changes. In which FBSession class is deprecated. So all users are suggested to migrate to new sdk and APIs.
Below I have mentioned, how we can get user details via Facebook SDK v4 :
if ([FBSDKAccessToken currentAccessToken]) {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:nil]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#”fetched user:%#”, result);
}
}];
}
But before fetching user details, we have to integrate new Facebook login in our code as described in Documentation here.
Here is the Changelog for SDK v4. I suggest going through it for being updated.
Add info.plist file:
- (IBAction)btn_fb:(id)sender
{
if (!FBSession.activeSession.isOpen)
{
NSArray *_fbPermissions = #[#"email",#"publish_actions",#"public_profile",#"user_hometown",#"user_birthday",#"user_about_me",#"user_friends",#"user_photos",];
[FBSession openActiveSessionWithReadPermissions:_fbPermissions 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 btn_fb:sender];
}
}];
return;
}
[FBRequestConnection startWithGraphPath:#"me" parameters:[NSDictionary dictionaryWithObject:#"cover,picture.type(large),id,name,first_name,last_name,gender,birthday,email,location,hometown,bio,photos" forKey:#"fields"] HTTPMethod:#"GET" completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
{
if (!error)
{
if ([result isKindOfClass:[NSDictionary class]])
{
NSLog(#"%#",result);
}
}
}
}];
}
Please refer these following links, sothat you can get some idea.
https://www.parse.com/tutorials/integrating-facebook-in-ios
Facebook iOS 6 - get user info
get Facebook user profile data after getting access token in iOS 5
Display a user's profile name and image through the Facebook instance for iOS
How to cache Facebook User Info with Facebook Login in IOS App
How do I get the full User object using Facebook Graph API and facebook ios sdk?
Hope it will helps you....
Use the FBConnect API for fetch user information.its easy to use
Fbconnect API
Hope it Works For you :)
you have to use graph path to get user Information.
-(void)getEmailId
{
[facebook requestWithGraphPath:#"me" andDelegate:self];
}
- (void)openSession
{
if (internetActive) {
NSArray *permissions=[NSArray arrayWithObjects:#"read_stream",#"email",nil];
[FBSession openActiveSessionWithReadPermissions:permissions allowLoginUI:YES completionHandler:
^(FBSession *session,
FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
}];
}else
{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"" message:#"Internet Not Connected" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
}
#pragma mark- request delegate methods
- (void)request:(FBRequest *)request didLoad:(id)result
{
NSLog(#"request did load successfully....");
// __block NSDictionary *dictionary=[[NSDictionary alloc] init];
if ([result isKindOfClass:[NSDictionary class]]) {
NSDictionary* json = result;
NSLog(#"email id is %#",[json valueForKey:#"email"]);
NSLog(#"json is %#",json);
[[NSUserDefaults standardUserDefaults] setValue:[json valueForKey:#"email"] forKey:#"fbemail"];
[self.viewController login:YES];
}
}
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error
{
UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:#"" message:#"Server not responding.." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertView show];
[self fblogout];
[self showLoginView];
NSLog(#"request did fail with error");
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen: {
//state open action
}
// Initiate a Facebook instance
facebook = [[Facebook alloc]
initWithAppId:FBSession.activeSession.appID
andDelegate:nil];
// Store the Facebook session information
facebook.accessToken = FBSession.activeSession.accessToken;
facebook.expirationDate = FBSession.activeSession.expirationDate;
if (![[NSUserDefaults standardUserDefaults] valueForKey:#"fbemail"]) {
[MBProgressHUD showHUDAddedTo:self.viewController.view animated:YES];
[self getEmailId];
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
// Once the user has logged in, we want them to
// be looking at the root view.
[self.navController popToRootViewControllerAnimated:NO];
[FBSession.activeSession closeAndClearTokenInformation];
facebook = nil;
[self showLoginView];
break;
default:
break;
}
[[NSNotificationCenter defaultCenter]
postNotificationName:FBSessionStateChangedNotification
object:session];
if (error) {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
FBRequest *request = [FBRequest requestForMe];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
// handle successful response
} else if ([error.userInfo[FBErrorParsedJSONResponseKey][#"body"][#"error"][#"type"] isEqualToString:#"OAuthException"]) { // Since the request failed, we can check if it was due to an invalid session
NSLog(#"The facebook session was invalidated");
[self logoutButtonTouchHandler:nil];
} else {
NSLog(#"Some other error: %#", error);
}
}];
Facebook has currently updated their SDK version to 4.x. To Fetch user's profile information you will need to explicitly call graph API after login success (ask for required permissions).
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"/me"
parameters:#{ #"fields": #"id,name,email"}
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
// Insert your code here
}];

Facebook SDK error 3 and error 2

I have this application I am using for posting on facebook and I am currently facing difficulties in posting on some of the iOS 6.0 devices. I am using facebook SDK 3.1 only and trying to publish action. Following is the code I am using in the class to initiate the read permission.
For the access I am using the following code.
// CALLING THIS CODE BLOCK IN ONE BUTTON ACTION.
if (FBSession.activeSession.isOpen)
{
[self pickaChoice];
}
else
{
[FBSession openActiveSessionWithPublishPermissions:[NSArray arrayWithObjects:#"publish_actions", nil]
defaultAudience:FBSessionDefaultAudienceEveryone
allowLoginUI:YES
completionHandler:
^(FBSession *session,
FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
}];
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state)
{
case FBSessionStateOpen:
[FBSession setActiveSession:session];
[self pickaChoice];
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
// Once the user has logged in, we want them to
// ...
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
break;
}
if (error) {
NSString* message = [NSString stringWithFormat:#"You have disallowed application to post on your behalf."];
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Error"
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[FBSession.activeSession closeAndClearTokenInformation];
}
}
-(void)pickaChoice
{
/* Just a class to select message and then retrieve the message in the next function
-(void)didSelectaPhraseToPost:(NSString *)message */
FBPublishViewController *fbPublishViewController = [[FBPublishViewController alloc] initWithNibName:#"FBPublishViewController"
bundle:[NSBundle mainBundle]];
fbPublishViewController.selectionDelegate = self;
[self presentViewController:fbPublishViewController
animated:YES
completion:^(){
//nil
}];
}
-(void)didSelectaPhraseToPost:(NSString *)message
{
// Selecting a message from a class and retrieving here. This is the message to post on the feed.
[self publishMessage:message];
}
- (void) performPublishAction:(void (^)(void)) action
{
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound) {
[FBSession.activeSession reauthorizeWithPublishPermissions:[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
action();
}
//For this example, ignore errors (such as if user cancels).
}];
} else {
action();
}
}
- (void)publishMessage:(NSString *)message
{
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"APP_NAME", #"name",
message, #"message",
APP_LINK, #"link",
#"APP_PICTURE", #"picture",
nil];
[self.spinner startAnimating];
[self performPublishAction:^{
[FBRequestConnection
startWithGraphPath:#"me/feed"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
[self.spinner stopAnimating];
NSString *messageTitle = nil;
NSString *message = nil;
// If the result came back okay with no errors...
if (result && !error)
{
NSLog(#"accessToken : %#",[FBSession activeSession].accessToken );
NSLog(#"result : %#",result);
messageTitle = #"Success";
message = #"App has posted to facebook";
}else{
NSLog(#"error : %#",error);
messageTitle = #"Error v1.1";
//message = error.localizedDescription;
message = #"Unable to process the request. Please check the permissions for the application.";
[FBSession.activeSession closeAndClearTokenInformation];
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:messageTitle
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
//TODO maybe clear connection here if we want to force an new login
}];
}];
}
Now the problem is on some iOS 6.0 devices it is throwing facebook.sdk.error 3 and on some devices it is throwing facebook.sdk.error 2 even when the application is permitted to post. In the current code I have just changed the message to a custom for more user friendly message but if you go on to print the localizedDescription it will show those.
On most of the iOS 6.0 devices the code is working absolutely fine and the message is posted. Let me know if anyone can find out where the problem exactly is. I have spent like days now in this and still not getting where the problem is.
Edit 1
A pattern I observed that when facebook application is installed and user is logged in through it and not logged in through the native settings I am facing these sort of difficulties.
It would be good if you find out your iOS version and use apple's default facebook shar view for iOS 6.0 and on another side for below version you must need to use Graph API.
I used this method its work for me fine in iOS6, may be its help you.
-(void)openFacebookAuthentication
{
NSArray *permission = [NSArray arrayWithObjects:kFBEmailPermission,kFBUserPhotosPermission, nil];
[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: {
NSString *errorCode = [[error userInfo] objectForKey:FBErrorLoginFailedOriginalErrorCode];
NSString *errorReason = [[error userInfo] objectForKey:FBErrorLoginFailedReason];
BOOL userDidCancel = !errorCode && (!errorReason || [errorReason isEqualToString:FBErrorLoginFailedReasonInlineCancelledValue]);
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;
}

facebook integration in iphone with Facebook sdk for ios5 and 6

i have use FAcebook sdk 3.0 to integrate facebook.I have use sample code "HelloFacebookSample"
to post status.
I have change in Info.plist file with my AppId.
I have problem that show armv7s,armv7 architecture problem.I even solve out that by "Build Active Architecture Only "to YEs.
I have code that show button for login/logout for facebook
#import "HFViewController.h"
#import "AppDelegate.h"
#import <CoreLocation/CoreLocation.h>
#interface HFViewController () <FBLoginViewDelegate>
#property (strong, nonatomic) IBOutlet UIButton *buttonPostStatus;
#property (strong, nonatomic) id<FBGraphUser> loggedInUser;
- (IBAction)postStatusUpdateClick:(UIButton *)sender;
- (void)showAlert:(NSString *)message
result:(id)result
error:(NSError *)error;
#end
#implementation HFViewController
#synthesize shareStringFb;
#synthesize buttonPostStatus = _buttonPostStatus;
#synthesize loggedInUser = _loggedInUser;
- (void)viewDidLoad {
[super viewDidLoad];
// Create Login View so that the app will be granted "status_update" permission.
self.buttonPostStatus.enabled = YES;
FBLoginView *loginview = [[FBLoginView alloc] init];
loginview.frame = CGRectOffset(loginview.frame, 5, 5);
loginview.delegate = self;
[self.view addSubview:loginview];
[loginview sizeToFit];
statusText.text=self.shareStringFb;
{
// if the session is closed, then we open it here, and establish a handler for state changes
}
}
-(IBAction)backClick:(id)sender
{
[self.view removeFromSuperview];
}
- (void)viewDidUnload {
self.buttonPostStatus = nil;
self.loggedInUser = nil;
[super viewDidUnload];
}
- (void)loginViewShowingLoggedInUser:(FBLoginView *)loginView {
// first get the buttons set for login mode
self.buttonPostStatus.enabled = YES;
}
- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView
user:(id<FBGraphUser>)user {
// here we use helper properties of FBGraphUser to dot-through to first_name and
// id properties of the json response from the server; alternatively we could use
// NSDictionary methods such as objectForKey to get values from the my json object
self.loggedInUser = user;
}
- (void)loginViewShowingLoggedOutUser:(FBLoginView *)loginView {
self.buttonPostStatus.enabled = NO;
}
// Post Status Update button handler
- (IBAction)postStatusUpdateClick:(UIButton *)sender {
// Post a status update to the user's feed via the Graph API, and display an alert view
// with the results or an error.
NSString *message = [NSString stringWithFormat:#"Updating %#'s status at %#",
self.loggedInUser.first_name, [NSDate date]];
[FBRequestConnection startForPostStatusUpdate:self.shareStringFb
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
[self showAlert:message result:result error:error];
self.buttonPostStatus.enabled = YES;
}];
self.buttonPostStatus.enabled = NO;
}
// Post Photo button handler
it show one button with login/logout in simulator but when i test in device it doesn't show that button.
Please any one can tell me what is problem?Why it not show that?Is there any other way to integrate Fb in ios 5 and 6 both.
Use for
this facebook sdk (3.1) for iOS6
ViewController.h
#import <FacebookSDK/FacebookSDK.h>
{
NSDictionary *dictionary;
NSString *user_email;
NSString *accessTokan;
NSMutableDictionary *fb_dict;
}
- (IBAction)btn_loginwithfacebook:(id)sender;
{
if (!FBSession.activeSession.isOpen)
{
// if the session is closed, then we open it here, and establish a handler for state changes
[FBSession openActiveSessionWithReadPermissions:nil 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 btn_loginwithfacebook:sender];
}
}];
return;
}
[FBRequestConnection startWithGraphPath:#"me" parameters:[NSDictionary dictionaryWithObject:#"picture,id,birthday,email,name,gender,username" forKey:#"fields"] HTTPMethod:#"GET" completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
if (!error)
{
if ([result isKindOfClass:[NSDictionary class]])
{
//NSDictionary *dictionary;
if([result objectForKey:#"data"])
dictionary = (NSDictionary *)[(NSArray *)[result objectForKey:#"data"] objectAtIndex:0];
else
dictionary = (NSDictionary *)result;
//NSLog(#"dictionary : %#",dictionary);
user_email = [dictionary objectForKey:#"email"];
[dictionary retain];
//NSLog(#"%#",user_email);//
}
}
}];
accessTokan = [[[FBSession activeSession] accessTokenData] accessToken];
//NSLog(#"%#",accessTokan);
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/me?access_token=%#",accessTokan]]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
//NSLog(#"%#",str);
fb_dict = [str JSONValue];
[str release];}
FacebookAppID ::370546396320150
URL types
Item 0
URL Schemes
Item 0 ::fb370546396320150

Get facebook user details in ios 6 sdk?

How to retrieve facebook user details with ios 6 inbuilt facebook sdk? I tried few examples, but couldn't get work.
- (void) getFBDetails {
if(!_accountStore)
_accountStore = [[ACAccountStore alloc] init];
ACAccountType *facebookTypeAccount = [_accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
[_accountStore requestAccessToAccountsWithType:facebookTypeAccount
options:#{ACFacebookAppIdKey: #"514284105262105", ACFacebookPermissionsKey: #[#"email"]}
completion:^(BOOL granted, NSError *error) {
if(granted){
NSArray *accounts = [_accountStore accountsWithAccountType:facebookTypeAccount];
_facebookAccount = [accounts lastObject];
NSLog(#"Success");
[self me];
}else{
// ouch
NSLog(#"Fail");
NSLog(#"Error: %#", error);
}
}];
}
- (void)me{
NSURL *meurl = [NSURL URLWithString:#"https://graph.facebook.com/me"];
SLRequest *merequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:meurl
parameters:nil];
merequest.account = _facebookAccount;
[merequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSString *meDataString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#", meDataString);
}];
}
But this fails to grab data from facebook. My app id is correct.
This the error message I got
Error: Error Domain=com.apple.accounts Code=7 "The Facebook server could not fulfill this access request: no stored remote_app_id for app" UserInfo=0x1d879c90 {NSLocalizedDescription=The Facebook server could not fulfill this access request: no stored remote_app_id for app}
Not sure if this will fix it or not, but have you set the Facebook App ID in your AppName-Info.plist file of your app?
The key required is FacebookAppID, which is of type String.
Try filling in your App ID there as well and see if it works.
In iOS6.0 ,you have to ask read and write permissions separately.
First ask for read permissions that is email then ask for other permissions according to the app requirement.
in .h file
#import <Accounts/Accounts.h>
#import <Social/Social.h>
#property (nonatomic, strong) ACAccountStore *accountStore;
#property (nonatomic, strong) ACAccount *facebookAccount;
in .m file
- (void) getuserdetails
{
self.accountStore = [[ACAccountStore alloc]init];
ACAccountType *FBaccountType= nil;
//[self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
if (! FBaccountType) {
FBaccountType = [_accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
}
NSString *key =kFBAppId;
NSDictionary *dictFB = [NSDictionary dictionaryWithObjectsAndKeys:key,ACFacebookAppIdKey,#[#"email"],ACFacebookPermissionsKey, nil];
[self.accountStore requestAccessToAccountsWithType:FBaccountType options:dictFB completion:
^(BOOL granted, NSError *e)
{
if (granted)
{
NSArray *accounts = [self.accountStore accountsWithAccountType:FBaccountType];
self.facebookAccount = [accounts lastObject];
NSLog(#"facebook account =%#",self.facebookAccount);
[self get];
}
else
{
NSLog(#"fb error %#",e.description);
dispatch_async(dispatch_get_main_queue(), ^
{
[self performSelectorOnMainThread:#selector(hideLoader) withObject:nil waitUntilDone:YES];
NSLog(#"%#",e.description);
if([e code]== ACErrorAccountNotFound)
{
UIAlertView* alt = [[UIAlertView alloc] initWithTitle:#"Account not found"
message:msgSetUpFBAccount delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok",nil];
[alt show];
}
else
{
UIAlertView* alt = [[UIAlertView alloc] initWithTitle:msgFBAccessDenied
message:#"" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok",nil];
[alt show];
}
});
NSLog(#"error getting permission %#",e);
}
}];
}
-(void)get
{
NSURL *requestURL = [NSURL URLWithString:#"https://graph.facebook.com/me"];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:requestURL
parameters:nil];
request.account = self.facebookAccount;
[request performRequestWithHandler:^(NSData *data,
NSHTTPURLResponse *response,
NSError *error)
{
if(!error)
{
list =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"Dictionary contains: %#", list );
if([list objectForKey:#"error"]!=nil)
{
[self attemptRenewCredentials];
}
dispatch_async(dispatch_get_main_queue(),^{
});
}
else
{
[self performSelectorOnMainThread:#selector(hideLoader) withObject:nil waitUntilDone:YES];
NSLog(#"error from get%#",error);
}
}];
}
-(void)attemptRenewCredentials{
[self.accountStore renewCredentialsForAccount:(ACAccount *)self.facebookAccount completion:^(ACAccountCredentialRenewResult renewResult, NSError *error){
if(!error)
{
switch (renewResult) {
case ACAccountCredentialRenewResultRenewed:
NSLog(#"Good to go");
[self get];
break;
case ACAccountCredentialRenewResultRejected:
{
NSLog(#"User declined permission");
UIAlertView* alt = [[UIAlertView alloc] initWithTitle:#"Access Denied"
message:#"You declined permission" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok",nil];
[alt show];
break;
}
case ACAccountCredentialRenewResultFailed:
{
NSLog(#"non-user-initiated cancel, you may attempt to retry");
UIAlertView* alt = [[UIAlertView alloc] initWithTitle:#"Access Denied"
message:#"non-user-initiated cancel, you may attempt to retry" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok",nil];
[alt show];
break;
}
default:
break;
}
}
else{
//handle error gracefully
NSLog(#"error from renew credentials%#",error);
}
}];
}
T**o get this code work the bundle Identifier with which you have registered your application with facebook and bundle identifier in application plist file should be same**

Posting to Facebook timeline from iOS gives HTTP 400 on first try

I'm following the tutorials set out on the facebook SDK:
Login with facebook using the ios SDK
Publish to Feed
Everything seems to work okay, except on testing my app, I get HTTP error 400 (or error code 5) on my first try at attempting to posting to the facebook wall. If I press my "Post" button again in the app, the second time, everything seems to work. On first try, the user is sent to the facebook app for authentication, and switches back to the app, then gives me the HTTP 400. On second try, there is no app switch, and the message is posted to the facebook wall as expected.
I'm trying to figure out why my app won't post to the wall/timeline on the first try. My code is the same as that in the tutorial.
Edit:
Forgot to mention, I'm using one button to both authenticate and post to the wall - this is the code in the IBAction:
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
// The user has initiated a login, so call the openSession method
// and show the login UX if necessary.
[appDelegate openSessionWithAllowLoginUI:YES];
[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 = [NSString stringWithFormat:
#"Posted action, id: %#", [result objectForKey:#"id"]];*/
alertText = #"Posted!";
}
// Show the result in an alert
[[[UIAlertView alloc] initWithTitle:#"Facebook" message:alertText delegate:self cancelButtonTitle:#"OK!" otherButtonTitles:nil] show];
}];
I solved this with mkral's helpful comments - code changed as follows:
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
if (FBSession.activeSession.isOpen) { //session is open so can post right away
[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!";
}
// Show the result in an alert
[[[UIAlertView alloc] initWithTitle:#"Facebook" message:alertText delegate:self cancelButtonTitle:#"OK!" otherButtonTitles:nil] show];
}];
}
else //session isn't open so authenticate first, then can post when back to app through notification
{
NSLog(#"Facebook Active Session not open");
// The user has initiated a login, so call the openSession method
// and show the login UX if necessary.
[appDelegate openSessionWithAllowLoginUI:YES];
}
So I first check if there's an active session - if there is I can just post to the wall/timeline, if not, I open a session. I then registered for a notification (in the viewDidLoad) to let me know if there's a session change (in this case there would be if a session opened) and it would then post to the wall once authenticated.
- (void)viewDidLoad
{
[super viewDidLoad];
//register for the session change notification you defined in the app delegate (for example when session changes to logged in)
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(sessionStateChanged:)
name:FBSessionStateChangedNotification
object:nil];
}
- (void)sessionStateChanged:(NSNotification*)notification {
if (FBSession.activeSession.isOpen) {
[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!";
}
// Show the result in an alert
[[[UIAlertView alloc] initWithTitle:#"Facebook" message:alertText delegate:self cancelButtonTitle:#"OK!" otherButtonTitles:nil] show];
}];
}
}