简体   繁体   English

检查accessstoken是否已过期Facebook SDK 4.7 ios

[英]Check if accesstoken is expired Facebook SDK 4.7 ios

I am using facebook sdk 4.7 and I need to check if accesstoken is expired. 我正在使用facebook sdk 4.7,我需要检查一下accessstoken是否已过期。

FBSDKAccessToken *access_token = [FBSDKAccessToken currentAccessToken];
    if (access_token != nil) {
        //user is not logged in

        //How to Check if access token is expired?
        if ([access_token isExpired]) {
            //access token is expired ......
            //
        }
    }

And if I success with that I have to log the user again. 如果我成功,我必须再次登录用户。

The SDK gives an expiration_date.how can that help? SDK提供expiration_date.how可以帮助吗? The device may have wrong date. 设备可能有错误的日期。

Assuming user has been logged in with Facebook before and has [FBSDKAccessToken currentAccessToken] != nil (I am not going into details here, because login via FB is another story). 假设用户之前已经使用Facebook登录并且[FBSDKAccessToken currentAccessToken] != nil (我在这里不会详细介绍,因为通过FB登录是另一个故事)。

In my app, I do the following to make sure the FB access token is always valid and synced with my app server. 在我的应用程序中,我执行以下操作以确保FB访问令牌始终有效并与我的应用服务器同步。

To keep it simple, all the code below is in AppDelegate.m 为了简单AppDelegate.m下面的所有代码都在AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // ...

    /** 
        Add observer BEFORE FBSDKApplicationDelegate's 
        application:didFinishLaunchingWithOptions: returns

        FB SDK sends the notification at the time it 
        reads token from internal cache, so our app has a chance 
        to be notified about this.
    */
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(fbAccessTokenDidChange:) 
                                                 name:FBSDKAccessTokenDidChangeNotification 
                                               object:nil];

    return [[FBSDKApplicationDelegate sharedInstance] application: application didFinishLaunchingWithOptions: launchOptions];
}

- (void)fbAccessTokenDidChange:(NSNotification*)notification
{
    if ([notification.name isEqualToString:FBSDKAccessTokenDidChangeNotification]) {

        FBSDKAccessToken* oldToken = [notification.userInfo valueForKey: FBSDKAccessTokenChangeOldKey];
        FBSDKAccessToken* newToken = [notification.userInfo valueForKey: FBSDKAccessTokenChangeNewKey];

        NSLog(@"FB access token did change notification\nOLD token:\t%@\nNEW token:\t%@", oldToken.tokenString, newToken.tokenString);

        // initial token setup when user is logged in
        if (newToken != nil && oldToken == nil) {

            // check the expiration data

            // IF token is not expired
            // THEN log user out
            // ELSE sync token with the server

            NSDate *nowDate = [NSDate date];
            NSDate *fbExpirationDate = [FBSDKAccessToken currentAccessToken].expirationDate;
            if ([fbExpirationDate compare:nowDate] != NSOrderedDescending) {
                NSLog(@"FB token: expired");

                // this means user launched the app after 60+ days of inactivity,
                // in this case FB SDK cannot refresh token automatically, so 
                // you have to walk user thought the initial log in with FB flow

                // for the sake of simplicity, just logging user out from Facebook here
                [self logoutFacebook];
            }
            else {
                [self syncFacebookAccessTokenWithServer];
            }
        }

        // change in token string
        else if (newToken != nil && oldToken != nil
            && ![oldToken.tokenString isEqualToString:newToken.tokenString]) {
            NSLog(@"FB access token string did change");

            [self syncFacebookAccessTokenWithServer];
        }

        // moving from "logged in" state to "logged out" state
        // e.g. user canceled FB re-login flow
        else if (newToken == nil && oldToken != nil) {
            NSLog(@"FB access token string did become nil");
        }

        // upon token did change event we attempting to get FB profile info via current token (if exists)
        // this gives us an ability to check via OG API that the current token is valid
        [self requestFacebookUserInfo];
    }
}

- (void)logoutFacebook
{
    if ([FBSDKAccessToken currentAccessToken]) {
        [[FBSDKLoginManager new] logOut];
    }
}

- (void)syncFacebookAccessTokenWithServer
{
    if (![FBSDKAccessToken currentAccessToken]) {
        // returns if empty token
        return;
    }

    // BOOL isAlreadySynced = ...
    // if (!isAlreadySynced) {
        // call an API to sync FB access token with the server
    // }
}

- (void)requestFacebookUserInfo
{
    if (![FBSDKAccessToken currentAccessToken]) {
        // returns if empty token
        return;
    }

    NSDictionary* parameters = @{@"fields": @"id, name"};
    FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:@"me"
                                                                   parameters:parameters];

    [request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
        NSDictionary* user = (NSDictionary *)result;
        if (!error) {
            // process profile info if needed
        }
        else {
            // First time an error occurs, FB SDK will attemt to recover from it automatically
            // via FBSDKGraphErrorRecoveryProcessor (see documentation)

            // you can process an error manually, if you wish, by setting
            // -setGraphErrorRecoveryDisabled to YES

            NSInteger statusCode = [(NSString *)error.userInfo[FBSDKGraphRequestErrorHTTPStatusCodeKey] integerValue];
            if (statusCode == 400) {
                // access denied
            }
        }
    }];
}

Each time you think it is good time to check FB token (eg an app was in background for a while), call -requestFacebookUserInfo . 每次你认为是检查FB令牌的好时机(例如应用程序在后台-requestFacebookUserInfo一段时间),请调用-requestFacebookUserInfo This will submit Open Graph request and returns an error if token is invalid/expired. 如果令牌无效/过期,这将提交Open Graph请求并返回错误。

for checking facebook permission..& give a permission...if permission exist then automatically get accesstoken other wise ask for login... 检查facebook权限..并给予许可...如果存在权限,则自动获取accessstoken其他明智的请求登录...

For Swift 对于斯威夫特

 var login: FBSDKLoginManager = FBSDKLoginManager()
login.logInWithReadPermissions(["public_profile", "email"], handler: { (result:FBSDKLoginManagerLoginResult!, error:NSError!) -> Void in

  if (error != nil)
  {
        //Process error
   }
   else if result.isCancelled
   {
        //Handle cancellations
   }
  else
  {
        // If you ask for multiple permissions at once, you
        // should check if specific permissions missing
        if result.grantedPermissions.contains("email"){
            //Do work
   }
     }
   })

For Objective c: 对于目标c:

check Permission like this. 检查这样的权限。 following code use .. 以下代码使用..

if ([[FBSDKAccessToken currentAccessToken]hasGranted:@"email"])
       {
          // add your coding here after login call this block automatically.
       }
       else
       {

    //login code  **//if accesstoken expired...then call this block**

    FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];

    [loginManager logInWithReadPermissions:@[@"public_profile", @"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error)




      }];

       }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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