how to refresh an oauth token when using the Facebook iPhone SDK

前端 未结 6 2009
被撕碎了的回忆
被撕碎了的回忆 2021-02-04 07:18

I\'m using the Facebook SDK for iOS in my app: http://github.com/facebook/facebook-ios-sdk

The oAuth token expires after about 2 hours. How can I \"refresh\" the oAuth

6条回答
  •  南方客
    南方客 (楼主)
    2021-02-04 08:20

    Since none of these answers actually addressed the question I am going to detail how I have implemented OAuth token refresh using The Facebook SDK.

    The SDK will automatically refresh your tokens when you make requests however, in my scenario we send the tokens to our servers and we need to use the latest token. So when our server indicates that we need new tokens this is what we do:

    Note You can either pass the AppID into the FBSession or you can add the FacebookAppID key to your App's plist (this is what we do).

    - (void)renewFacebookCredentials {
        if (FBSession.activeSession.state == FBSessionStateOpen ||
            FBSession.activeSession.state == FBSessionStateOpenTokenExtended) {
            [self sessionStateChanged:[FBSession activeSession] state:[FBSession activeSession].state error:nil];
        } else {
            // Open a session showing the user the login UI
            // You must ALWAYS ask for public_profile permissions when opening a session
            [FBSession openActiveSessionWithReadPermissions:@[@"public_profile",@"email"]
                                               allowLoginUI:NO
                                          completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
                                              //this block will run throughout the lifetime of the app.
                                              [self sessionStateChanged:session state:state error:error];
                                          }];
        }
    }
    

    The you can use the sessionStateChanged: method that Facebook include in their documentation but a simplified handler looks like this:

    - (void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error {
        // If the session was opened successfully
        NSString *accessToken;
        if (!error && state == FBSessionStateOpen && [[session accessTokenData] accessToken]){
            // Show the user the logged-in UI
    
            //@see http://stackoverflow.com/questions/20623728/getting-username-and-profile-picture-from-facebook-ios-7
            accessToken = [[session accessTokenData] accessToken];
           //Now we have an access token, can send this to the server...
        } else {
           //No access token, show a dialog or something
        }
    
       //either call a delegate or a completion handler here with the accessToken
    }
    

    Be aware that some of the FBSession API calls check for thread affinity so I found that I had to wrap all my FBSession calls inside a dispatch_async(dispatch_get_main_queue(), ^{...

提交回复
热议问题