I am using iOS facebook SDK 3.0. How can i check if the user is already logged in?
I tried the line below but it does not work properly. It sometimes returns NO although I am logged in. Any suggestions?
if (FBSession.activeSession.isOpen == YES)
{
// post to wall else login
}
-- EDIT --
this is how I open my Facebook session:
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"user_likes",
#"read_stream",
#"publish_actions",
nil];
return [FBSession openActiveSessionWithPermissions:permissions
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
[self sessionStateChanged:session
state:state
error:error];
}];
The first time it needs login and so it works. If i try this while I am already logged in the FBSession.activeSession.isOpen returns NO.
You can check if you have a valid token by trying to open a new session without allowing the
login UI
if (FBSession.activeSession.isOpen)
{
// post to wall
} else {
// try to open session with existing valid token
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"user_likes",
#"read_stream",
#"publish_actions",
nil];
FBSession *session = [[FBSession alloc] initWithPermissions:permissions];
[FBSession setActiveSession:session];
if([FBSession openActiveSessionWithAllowLoginUI:NO]) {
// post to wall
} else {
// you need to log the user
}
}
If you are using FBSDK greater then 4.x then there is no concept of FBSession. You have to find the active session only by using [FBSDKAccessToken currentAccessToken] simply check if it has nil value, no active session else it is.
Instead, you should check [FBSDKAccessToken currentAccessToken] at
viewDidLoad or similar. If a current token is available, do the
post-login work. You can also use currentAccessToken to retrieve
cached tokens.
you can find more here https://developers.facebook.com/docs/ios/upgrading-4.x
FBSession.activeSession has been replaced with [FBSDKAccessToken currentAccessToken] and FBSDKLoginManager. There is no concept of
session state. Instead, use the manager to login and this sets the
currentAccessToken reference.
i did it as in the Facebook example
if (FBSession.activeSession.state == FBSessionStateCreatedTokenLoaded)
{
}
The session is active if the state is either in FBSessionStateOpen or in FBSessionStateOpenTokenExtended. You can use the function below to check if the user is logged in:
- (BOOL)isSessionOpen
{
return FBSession.activeSession.state == FBSessionStateOpen || FBSession.activeSession.state == FBSessionStateOpenTokenExtended;
}
How are you opening your FBSession?
If you're creating an instance, be sure to set FBSession.activeSession. That was my issue for a while.
if ([FBSDKAccessToken currentAccessToken])
{
NSLog(#"Already login");
//[FBSession openActiveSessionWithAllowLoginUI: YES];
}
Related
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?
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 ? refer screen short.
I give login details, after click login button that blank screen will appear after this no response from SDK and not return to App.
can anyone help me for this ?
add this code to your AppDelegate
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation
{
return [FBSession.activeSession handleOpenURL:url];
}
read more :https://developers.facebook.com/docs/ios/login-tutorial
I am using FB ios SDK v3.5 for my app. For log in part, I don't use FBLoginView to log in, instead, I use a UIButton and invoke [FBSession openActiveSessionWithReadPermission] in the handler of that UIButton.
In FB SDK v3.2.1, I use the following code to handle different log in scenarios, it works fine:
self.useAccountAllowed = true;
ACAccountStore *accountStore;
ACAccountType *accountTypeFB;
if ((accountStore = [[ACAccountStore alloc] init]) &&
(accountTypeFB = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook] ) ){
NSArray *fbAccounts = [accountStore accountsWithAccountType:accountTypeFB];
id account;
if (!fbAccounts)
{
//do not log into FB on the device
}
else if ([fbAccounts count] == 0) {
[FBSession.activeSession closeAndClearTokenInformation];
self.useAccountAllowed = false; //User does not allow the app to use the account
}
else if ([fbAccounts count]>0 && (account=[fbAccounts objectAtIndex:0])) {
[accountStore renewCredentialsForAccount:account completion:^(ACAccountCredentialRenewResult renewResult, NSError *error) { //User allowes the app to use the account
//we don't actually need to inspect renewResult or error.
if (error){
}
}];
}
}
then in the handler function of the UIButton:
if (self.useAccountAllowed) {
[FBSession openActiveSessionWithReadPermissions:nil allowLoginUI:YES completionHandler:^(FBSession* session, FBSessionState status, NSError* error){
[self sessionStateChanged:session state:status error:error];}];
}
else {
NSArray* lPermission = FBSession.activeSession.permissions;
[FBSession openActiveSessionWithPermissions:lPermission allowLoginUI:YES completionHandler:^(FBSession* session, FBSessionState status, NSError* error){
[self sessionStateChanged:session state:status error:error];}];
which means that if User does not allow the app to use the account, we just use fast-switch way through Safari to login; otherwise we use the native login.
But in SDK v3.5, still the same code, but sometimes when the app is executed and logged into facebook, the app is not in the "Allow these apps to Use your Account" list, so this code cannot distinguish these two cases: 1.the app is not in the list; 2. user disallows the app to use this account. so the app fails to log in natively.
Notice that this problem exists randomly. sometimes I hard code to invoke openActiveSessionWithPermissions directly, this problem is gone. but I am not sure it is the reason.
I just wonder in FB SDK v3.5, do I need to explicitly invoke some SDK function that is related to iOS settings?
I'm following example of facebook authentication
https://developers.facebook.com/docs/tutorials/ios-sdk-games/authenticate/
for Login i've used:
[FBSession openActiveSessionWithPermissions:permissions allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if (session.isOpen)
{
appDelegate.session=session;
}
}//end completionHandler
];
and for facebook apprequest dialog:
if (nil == appDelegate.facebook)
{
appDelegate.facebook = [[Facebook alloc]
initWithAppId:FBSession.activeSession.appID
andDelegate:nil];
// Store the Facebook session information
appDelegate.facebook.accessToken = FBSession.activeSession.accessToken;
appDelegate.facebook.expirationDate = FBSession.activeSession.expirationDate;
}
[self.facebook dialog:APPREQUEST
andParams:params
andDelegate:self];
after some time when i try to run app again then app is connected to facebook and FBSession is also active, but when i call apprequest dialog then it asks for login.
is there any problem with appDelegate.facebook = [[Facebook alloc] or my session is expired?
Any suggestion please?
Try placing your Facebook object session setting code inside the completion handler. The completion handler should be called whenever the session changes, for example, later on when the token is extended, it should be called again. That way you can keep the Facebook object session refreshed. You should not have to extend the access token yourself, the SDK now does that automatically for you.
[FBSession openActiveSessionWithPermissions:permissions
allowLoginUI:YES
completionHandler:
^(FBSession *session, FBSessionState status, NSError *error) {
if (session.isOpen)
{
appDelegate.session=session;
if (nil == appDelegate.facebook)
{
appDelegate.facebook = [[Facebook alloc]
initWithAppId:FBSession.activeSession.appID
andDelegate:nil];
}
// Store the Facebook session information
appDelegate.facebook.accessToken = FBSession.activeSession.accessToken;
appDelegate.facebook.expirationDate = FBSession.activeSession.expirationDate;
} // if session open
else
{
appDelegate.facebook = nil;
} // session not open
} //end completionHandler
];
We use Facebook SSO in our application. On clicking Facebook login app goes to Facebook app, displays login. But after login it won't return to app. But if a user is already logged in Facebook app, login button click switches to Facebook app and shows permission dialog. On clicking allow it returns to app. Is it the default behavior? Or is there any problem with my code or our Facebook app settings? Thanks in advance.
SHAppDelegate *appDelegate = [SHAppDelegate application];
NSArray * permissions = [[NSArray alloc]initWithObjects:FACEBBOK_PERMISSION, nil];
if (!appDelegate.session.isOpen) {
appDelegate.session = [[[FBSession alloc] initWithPermissions:permissions] autorelease];
if (appDelegate.session.state == FBSessionStateCreatedTokenLoaded) {
[appDelegate.session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
[self updateView];
}];
}
}
if (appDelegate.session.isOpen) {
[appDelegate.session closeAndClearTokenInformation];
} else
{
if (appDelegate.session.state != FBSessionStateCreated) {
// Create a new, logged out session.
appDelegate.session = [[FBSession alloc] init];
}
// 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) {
// and here we make sure to update our UX according to the new session state
[self updateView];
}];
}
I have the same issue. This is not a .plist trouble - without URLSchemes(with fbXXXXX) facebook app and safari never return to you application.
In this case, the Faccebook app does not return only when the user is not logged in it.
Safari handles this situation correctly. The same way a Facebook app does not return control if the user canceled the permissions confirmation.
In other situations, all right.