简体   繁体   中英

Facebook login in iOS app for multiple users on one device

My app will be used by multiple users.

How can I integrate facebook in a way so that the safari doesn't save any user credentials & throw a login page each time some one tries to login.

I already used FBSessionLoginBehaviorForcingWebView to force a web view login within the app but the problem is, when the first user tries to login to fb via the view presented within the app, the control then goes to safari for authentication & it just saves the creds.

So when other user tries to log in, & enters his credentials in the app local UIWebView, the control again goes to safari, which already has previos creds stored & the new user just cannot authenticate.

So basically the first user is permanently logged in. Clearing the cookies for web view doesn't work. I cant clear them for safari.

Help Thanks in advance.

This is what I have been doing

if([FBSession activeSession].isOpen)
{
   [[FBSession activeSession] closeAndClearTokenInformation];//Also, clearing all the local cookies
}
else
{
  AppDelegate *delegate = [UIApplication sharedApplication].delegate;
  delegate.session = [[FBSession alloc] init];
  [FBSession setActiveSession:delegate.session];
  [delegate.session openWithBehavior:FBSessionLoginBehaviorForcingWebView    completionHandler:^(FBSession *session1, FBSessionState status, NSError *error) {
    if (!error) {
       [self openSession]; // your method
    }
   }];
 }


- (void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error{
switch (state) {
    case FBSessionStateOpen:
    {
        [FBRequestConnection startForPostStatusUpdate:@"Some message"completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
            if (!error) {

                //logout again
                NSLog(@"startForPostStatusUpdate SUCESS");
            }
            else {
                //logout again
                NSLog(@"startForPostStatusUpdate FAIL");
            }
        }];

    }
        break;
    case FBSessionStateClosed:
    {
        NSLog(@"FBSessionStateClosed");
    }
        break;
    case FBSessionStateClosedLoginFailed:
        [FBSession.activeSession closeAndClearTokenInformation];
        break;
    default:
        break;
}
if (error) {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alertView show];
}
}

Also, modified the app delegate with your methods.

Found a solution. Basically, calling the following:

[FBSession.activeSession closeAndClearTokenInformation];
[FBSession.activeSession close];
[FBSession setActiveSession:nil];

Only clears the local FB session information but not the Safari cookies. So, after I log in the user, I clear the Safari cookies:

NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies]) {
    [storage deleteCookie:cookie];
}
[[NSUserDefaults standardUserDefaults] synchronize];

It isn't very elegant, but it works. Now, when the next user tries to log in, it forces them to enter their credentials.

You just need to use this method after you want to close the FB Session.

[FBSession.activeSession closeAndClearTokenInformation];

This will clear the Facebook Token, and whenever button will be pressed for Facebook share, it will ask for new token credential and it will show Facebook login view again.

Use following code in AppDelegate

    // This method will handle facebook session.
    - (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
    {
    // Facebook SDK * login flow *
    // Attempt to handle URLs to complete any auth (e.g., SSO) flow.
    return [FBAppCall handleOpenURL:url sourceApplication:sourceApplication fallbackHandler:^(FBAppCall *call) {
        // Facebook SDK * App Linking *
        // For simplicity, this sample will ignore the link if the session is already
        // open but a more advanced app could support features like user switching.
        if (call.accessTokenData) {
            if ([FBSession activeSession].isOpen) {
                NSLog(@"INFO: Ignoring app link because current session is open.");
            }
            else {
                [self handleAppLink:call.accessTokenData];
            }
        }
    }];
}


// Helper method to wrap logic for handling app links.
- (void)handleAppLink:(FBAccessTokenData *)appLinkToken {
    // Initialize a new blank session instance...
    FBSession *appLinkSession = [[FBSession alloc] initWithAppID:nil
                                                     permissions:nil
                                                 defaultAudience:FBSessionDefaultAudienceNone
                                                 urlSchemeSuffix:nil
                                              tokenCacheStrategy:[FBSessionTokenCachingStrategy nullCacheInstance] ];
    [FBSession setActiveSession:appLinkSession];
    // ... and open it from the App Link's Token.
    [appLinkSession openFromAccessTokenData:appLinkToken
                          completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
                              // Forward any errors to the FBLoginView delegate.
                              if (error) {
                                  //TODO: Show error here
                              }
                          }];
}

Add following code where you are opening session for Facebook

/***********************************************************************
 This method opens browser or App Url to FB authentication and change FB
 session state
 ************************************************************************/
- (void)openSession
{
    NSArray *permisssions = [[NSArray alloc] initWithObjects:@"email",@"user_photos",nil];
    [FBSession openActiveSessionWithReadPermissions:permisssions
                                       allowLoginUI:YES
                                  completionHandler:
     ^(FBSession *session,
       FBSessionState state, NSError *error) {
         [self sessionStateChanged:session state:state error:error];
     }];
}




/***********************************************************************
 This method will be called whenever FB Session state changed
 It also shows an error message if any error occurs
 ************************************************************************/
- (void)sessionStateChanged:(FBSession *)session
                      state:(FBSessionState) state
                      error:(NSError *)error
{
    switch (state) {
        case FBSessionStateOpen: {
            NSLog(@"FBSession Open State");
            //Enter your code what you want to perform when session is open
        }
            break;
        case FBSessionStateClosed:
        case FBSessionStateClosedLoginFailed:
            // Once the user has logged in, we want them to
            // be looking at the root view.
            NSLog(@"FBSession State Closed");

             [FBSession.activeSession closeAndClearTokenInformation];
             [FBSession.activeSession close];
             [FBSession setActiveSession:nil];
            break;
        default:
            break;
    }

    if (error) {
        UIAlertView *alertView = [[UIAlertView alloc]
                                  initWithTitle:@"Error"
                                  message:error.localizedDescription
                                  delegate:nil
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil];
        [alertView show];
    }
}

Now when ever user tap on Facebook Share button check that session exists or not. If not then call openSession method. It will open facebook login view.

There is a sample in the Facebook Github repository , showing how to switch between multiple users.

It looks like it requires use of the custom login flow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM