FBRequest requestForMe does not respond - ios

I am following the sample codes on Facebook developer's site and I cannot fetch my name for example. I am using this code:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
if (!appDelegate.session.isOpen) {
NSLog(#"Session is not open");
// create a fresh session object
appDelegate.session = [[FBSession alloc] init];
// if we don't have a cached token, a call to open here would cause UX for login to
// occur; we don't want that to happen unless the user clicks the login button, and so
// we check here to make sure we have a token before calling open
if (appDelegate.session.state == FBSessionStateCreatedTokenLoaded) {
// even though we had a cached token, we need to login to make the session usable
[appDelegate.session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
// we recurse here, in order to update buttons and labels
}];
}
} else {
NSLog(#"Session is open");
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
NSLog(#"logged in : %#, id: %#",user.name,user.id);
} else {
NSLog(#"error: %#", error);
}
}];
}
}
so when the session is open, I see this output:
Session is open
error: Error Domain=com.facebook.sdk Code=5 "The operation couldn’t be completed. (com.facebook.sdk error 5.)" UserInfo=0x1fd60620 {com.facebook.sdk:ParsedJSONResponseKey={
body = {
error = {
code = 2500;
message = "An active access token must be used to query information about the current user.";
type = OAuthException;
};
};
code = 400;
}, com.facebook.sdk:HTTPStatusCode=400}
On facebook app page, I have set AppId to 0 since it is not uploaded yet. BundleId is set correctly.
What am I missing or is there any other way to do so?

You should set your appDelegate.session as the active session by calling
[FBSession setActiveSession:appDelegate.session];
when you open it.
This is because FBRequest's requestForMe method uses the active session (as stated in the docs).

Related

cannot open session or publish post to facebook

For some reason the pffacebookutils session does not open/remain open.
I cannot publish to facebook and am getting this error. I assure you the currentuser is linked with facebook.
if ([[PFFacebookUtils session] isOpen]) {
/*
* if the current session has no publish permission we need to reauthorize
*/
if ([[[PFFacebookUtils session] permissions]indexOfObject:#"publish_actions"] == NSNotFound) {
[[PFFacebookUtils session] requestNewPublishPermissions:#[#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session,NSError *error){
[self publishFacebookStory: object message:message];
}];
}else{
[self publishFacebookStory: object message:message];
}
}else{
/*
* open a new session with publish permission
*/
[[PFFacebookUtils session] openWithCompletionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if (!error && status == FBSessionStateOpen) {
[self publishFacebookStory: object message:message];
}else{
NSLog(#"%#",error);
}
}];
}
Some related error output:
FBSDKLog: Error for request to endpoint '/me/fitness.runs': An open FBSession must be specified for calls to this endpoint.
Error Domain=com.facebook.sdk Code=5 "The operation couldn’t be completed. (com.facebook.sdk error 5.)" UserInfo=0x17547aa80 {com.facebook.sdk:HTTPStatusCode=400, com.facebook.sdk:ParsedJSONResponseKey={
body = {
error = {
code = 2500;
message = "An active access token must be used to query information about the current user.";
type = OAuthException;
};
};
code = 400;
}}
PFKeychainStore failed to get object for key 'currentUser'
thanks for any help!
This was temporarily fixed, and I actually no longer recall what the actual issue was...but I now use parse facebook utils v4 and facebook sdk 4.0+ and the issue no longer exists because there is no such thing as sessions anymore.

iOS using Facebook graph API for post without share dialog?

I want to use Facebook graph API to share on Facebook through my app, without presenting share dialog.But on reading various threads on internet i'm really confused about how to achieve this. i found this post on stack overflow but didn't able to find out how to make it works.
Can anyone give me step by step guideline or source code. any help would be highly appreciated.
Edit: code i used so far-
- (IBAction)StatusUpdateWithAPICalls:(id)sender {
[self openSessionForReadPermissions];
}
- (void)openSessionForReadPermissions
{
[FBSession openActiveSessionWithReadPermissions:nil
allowLoginUI:YES
completionHandler:
^(FBSession *session,
FBSessionState state, NSError *error) {
//this is called even from the reauthorizeWithPublishPermissions
if (state == FBSessionStateOpen && !error)
{
//[self openSessionForPublishPermissions];
//dispatch_async(dispatch_get_current_queue(), ^{
[self openSessionForPublishPermissions];
//});
}
else if (state == FBSessionStateClosedLoginFailed)
{
[FBSession.activeSession closeAndClearTokenInformation];
// [[NSNotificationCenter defaultCenter] postNotificationName:FBLoginErrorNotification object:session];
}
}];
}
-(void)openSessionForPublishPermissions
{
// We will post on behalf of the user, these are the permissions we need:
NSArray *permissionsNeeded = #[#"publish_actions"];
// Request the permissions the user currently has
[FBRequestConnection startWithGraphPath:#"/me/permissions"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error){
// Parse the list of existing permissions and extract them for easier use
NSMutableArray *currentPermissions = [[NSMutableArray alloc] init];
NSArray *returnedPermissions = (NSArray *)[result data];
for (NSDictionary *perm in returnedPermissions) {
if ([[perm objectForKey:#"status"] isEqualToString:#"granted"]) {
[currentPermissions addObject:[perm objectForKey:#"permission"]];
}
}
// Build the list of requested permissions by starting with the permissions
// needed and then removing any current permissions
NSMutableArray *requestPermissions = [[NSMutableArray alloc] initWithArray:permissionsNeeded copyItems:YES];
[requestPermissions removeObjectsInArray:currentPermissions];
NSLog(#"Asking: %#", requestPermissions);
// If we have permissions to request
if ([requestPermissions count] > 0){
// Ask for the missing permissions
[FBSession.activeSession requestNewPublishPermissions:requestPermissions
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
// Permission granted, we can request the user information
[self makeRequestToUpdateStatus];
} else {
// An error occurred, handle the error
NSLog(#"%#", error.description);
}
}];
} else {
// Permissions are present, we can request the user information
[self makeRequestToUpdateStatus];
}
} else {
// There was an error requesting the permission information
// See our Handling Errors guide: https://developers.facebook.com/docs/ios/errors/
NSLog(#"%#", error.description);
}
}];
}
- (void)makeRequestToUpdateStatus {
// NOTE: pre-filling fields associated with Facebook posts,
// unless the user manually generated the content earlier in the workflow of your app,
// can be against the Platform policies: https://developers.facebook.com/policy
[FBRequestConnection startForPostStatusUpdate:#"User-generated status update."
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
// Status update 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);
}
}];
}
but i getting this error-
Error Domain=com.facebook.sdk Code=2 "The operation couldn’t be completed. com.facebook.sdk:ErrorReauthorizeFailedReasonUserCancelled" UserInfo=0x78788e60 {com.facebook.sdk:ErrorLoginFailedReason=com.facebook.sdk:ErrorReauthorizeFailedReasonUserCancelled, NSLocalizedFailureReason=com.facebook.sdk:ErrorReauthorizeFailedReasonUserCancelled, com.facebook.sdk:ErrorSessionKey=<FBSession: 0x787ac750, state: FBSessionStateOpen, loginHandler: 0x787ac710, appID: 4201XXXXXXXXXXX, urlSchemeSuffix: , tokenCachingStrategy:<FBSessionTokenCachingStrategy: 0x7a1c1b50>, expirationDate: 2015-04-20 06:48:00 +0000, refreshDate: 2015-02-19 09:39:47 +0000, attemptedRefreshDate: 0000-12-30 00:00:00 +0000, permissions:(
"public_profile"
)
And i'm not sure if i'm doing it right. please suggest me.
Use fallbacks.
Upload a photo via an app. FB logged in account

Can't get permissions for user_birthday and user_hometown in facebook-ios-sdk

I am not able to get the permissions for user_birthday and user_hometown.
I tried it with this code before but it only asks for the public profile and ignores others.
[FBSession openActiveSessionWithReadPermissions:#[#"public_profile",#"user_birthday",#"user_hometown"]
allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if (error) {
NBAppDelegate* appDel = (NBAppDelegate*)`[UIApplication sharedApplication].delegate;
[appDel sessionStateChanged:session state:status error:error];
}
if ([session isOpen]) {
[self loginWithFBToken:session name:sender];
}
}];
Then someone suggested to ask for additional permissions after getting the public profile, so i even tried that to no good.
Here is the code for that
- (void)loadFbDetails
{
NSArray *permissionsNeeded = #[#"user_hometown", #"user_birthday"];
// Request the permissions the user currently has
[FBRequestConnection startWithGraphPath:#"/me/permissions"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error){
// These are the current permissions the user has:
NSDictionary *currentPermissions= [(NSArray *)[result data] objectAtIndex:0];
// We will store here the missing permissions that we will have to request
NSMutableArray *requestPermissions = [[NSMutableArray alloc] initWithArray:#[]];
// Check if all the permissions we need are present in the user's current permissions
// If they are not present add them to the permissions to be requested
for (NSString *permission in permissionsNeeded){
if (![currentPermissions objectForKey:permission]){
[requestPermissions addObject:permission];
}
}
// If we have permissions to request
if ([requestPermissions count] > 0){
// Ask for the missing permissions
[FBSession.activeSession
requestNewReadPermissions:requestPermissions
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
// Permission granted
NSLog(#"new permissions %#", [FBSession.activeSession permissions]);
// We can request the user information
[self makeRequestForUserData];
} else {
// An error occurred, we need to handle the error
// See: https://developers.facebook.com/docs/ios/errors
}
}];
} else {
// Permissions are present
// We can request the user information
[self makeRequestForUserData];
}
} else {
// An error occurred, we need to handle the error
// See: https://developers.facebook.com/docs/ios/errors
}
}];
}
-(void)makeRequestForUserData
{
[FBRequestConnection startWithGraphPath:#"me?fields=birthday,hometown"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
// Sucess! Include your code to handle the results here
NSLog(#"user events: %#", result);
} else {
NSLog(#"error: %#" , error);
}
}];
}
All it does is recursively go between my ios app and the fb native app, returning only with the public_profile in the permissions array.
Looks like i am missing something?
It should work if you're using an admin user of the app. Once you want to use the extended permissions with other users, you have to get your app reviewed by Facebook first.
See my answer here: facebook extended permission
Facebook does not allow apps to access that information by default. You have to ask permission to Facebook for you to be able to use that information. Add a video and instructions for a Facebook employee review how you're using birthday and hometown intel.

How to get access token from FBSession?

I am using the Facebook SDK in order to get user groups in an application
but I am getting a null access token.
My code in viewDidLoad is as follows.
- (void)viewDidLoad
{
[super viewDidLoad];
self.session = [[FBSession alloc] initWithAppID:appID permissions:#[#"basic_info",#"user_groups",#"email"] defaultAudience:FBSessionDefaultAudienceEveryone urlSchemeSuffix:nil tokenCacheStrategy:nil];
[FBSession openActiveSessionWithReadPermissions:#[#"basic_info",#"user_groups",#"email"] allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
NSLog(#"Error in Session Opening %#",error.description);
NSLog(#"access Token %#",session.accessTokenData.accessToken);
[FBRequestConnection startWithGraphPath:#"me/groups" parameters:nil HTTPMethod:#"GET" completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"%#",result);
}else
{
NSLog(#"Error %#",error.description);
}
}];
}];
}
OUTPUT of this code is :-
Error in Session Opening (null)
access Token (null)
Error Error Domain=com.facebook.sdk Code=5 "The operation couldn’t be completed. (com.facebook.sdk error 5.)" UserInfo=0x1090acc80 {com.facebook.sdk:HTTPStatusCode=400, com.facebook.sdk:ParsedJSONResponseKey={
body = {
error = {
code = 2500;
message = "An active access token must be used to query information about the current user.";
type = OAuthException;
};
};
code = 400;
}}
As you can see the access token is null..
What am I doing wrong ?
Is there something extra which should be added in this code ?
Thanks
you want this:
session.accessTokenData.accessToken
where 'session' is your FBSession
which you can get from...
if (FBSession.activeSession.state == FBSessionStateCreatedTokenLoaded)
{
// If there's one, just open the session silently, without showing the user the login UI
[FBSession openActiveSessionWithReadPermissions:#[#"public_profile", #"email"]
allowLoginUI:NO
completionHandler:^(FBSession *session, FBSessionState state, NSError *error)
{
NSLog(#"%#", session.accessTokenData.accessToken);
}];
}
Are you using the correct facebook appID? Why not specify nil, i.e.,
self.session = [[FBSession alloc] initWithAppID:nil permissions:#[#"basic_info",#"user_groups",#"email"] defaultAudience:FBSessionDefaultAudienceEveryone urlSchemeSuffix:nil tokenCacheStrategy:nil];
That'd be one less place to go wrong. As it says in FBSession class reference
If nil is passed in the default App ID will be obtained from a call to
<[FBSession defaultAppID]>. The default is nil.
Also, you don't have to alloc/init the FBSession yourself, but if you want to, you should follow the 3-step process specified in FBSession lifecycle, including checking for FBSessionStateCreated before proceeding with one of the open methods, as quoted from FBSession lifecycle:
Instead of calling one of the static openActiveSession* methods, your app can achieve the same flow following these steps:
Call one of the FBSession instance init functions.
Check if the state value has transitioned to FBSessionStateCreated.
If the state value is FBSessionStateCreated, call one of the
FBSession instance
open functions.

Login via facebook sdk in ios

I'm using facebook-ios-sdk-3.10, Using this SDK I'll login and fetch user details from FB Its working fine for me.
This is the code I'm uisng
- (IBAction)fbLogin_click:(id)sender
{
if (AppDelegate.fbsession.state != FBSessionStateCreated) {
// Create a new, logged out session.
NSArray *permissions = [NSArray arrayWithObjects:#"offline_access", #"email", #"publish_stream", #"read_stream",#"read_friendlists",#"manage_friendlists",#"friends_about_me",#"publish_actions", nil];
// create a session object, with defaults accross the board, except that we provide a custom
// instance of FBSessionTokenCachingStrategy
AppDelegate.fbsession = [[FBSession alloc] initWithAppID:nil
permissions:permissions
urlSchemeSuffix:nil
tokenCacheStrategy:nil];
}
FBSessionLoginBehavior behavior = FBSessionLoginBehaviorForcingWebView;
if (AppDelegate.fbsession.state != FBSessionStateCreatedTokenLoaded) {
// even though we had a cached token, we need to login to make the session usable
[AppDelegate.fbsession openWithBehavior:behavior completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
if (error)
{
NSLog(#"Error");
}
[self GetFBUserDetails];
}];
}
}
-(void) GetFBUserDetails
{
if (AppDelegate.fbsession.isOpen)
{
[HUD show:YES];
// fetch profile info such as name, id, etc. for the open session
FBRequest *me = [[FBRequest alloc] initWithSession:AppDelegate.fbsession graphPath:#"me"];
self.pendingRequest= me;
[me startWithCompletionHandler:^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *user,
NSError *error) {
// because we have a cached copy of the connection, we can check
// to see if this is the connection we care about; a prematurely
// cancelled connection will short-circuit here
if (me != self.pendingRequest) {
return;
}
self.pendingRequest = nil;
// self.pendingLoginForSlot = -1;
// we interpret an error in the initial fetch as a reason to
// fail the user switch, and leave the application without an
// active user (similar to initial state)
if (error) {
return;
}
[AppDelegate.fbsession closeAndClearTokenInformation];
[FBSession.activeSession close];
[FBSession.activeSession closeAndClearTokenInformation];
FBSession.activeSession=nil;
[self FacebookCustomerRegister:user];
}];
}
}
In such case some user create Facebook account and not very his account through email, when he try to login via my app it shows empty screen after click login button, there is no action further. how can I notify the user "You not yet verify your FB account" and it not return to my app. how can I fetch the response from there ?
can anyone help me for this ?
The email address you get from Facebook using the Graph API or a FQL query is a verified email. If an account hasn't verified it's email yet it's not possible to get it.
so when you fetch user info and if you are not getting the email when you have the permission to get then user is no verified and you can show an alert or any info to user about verifying the email and information
check more detail here Is it possible to check if an email is confirmed on Facebook?

Resources