Social API Facebook iOS:“验证访问令牌时出错:会话已过期”

时间:2014-04-18 16:15:17

标签: ios objective-c facebook facebook-graph-api facebook-access-token

在我的iOS应用程序中,我使用社交框架Facebook API来请求与Facebook共享,但现在我从Facebook收到此状态代码:

{
    error =     {
        code = 190;
        "error_subcode" = 463;
        message = "Error validating access token: Session has expired on 25 marzo 2014 16.20. The current time is 18 aprile 2014 8.45.";
        type = OAuthException;
    };
}

这是我使用的代码:

ACAccountType *facebookTypeAccount = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];

NSDictionary *options = @{ACFacebookAppIdKey: @"##myfbid###",ACFacebookPermissionsKey: @[@"email"]};

[accountStore requestAccessToAccountsWithType:facebookTypeAccount
    options:options
    completion:^(BOOL granted, NSError *error) {
        if(granted){
            NSArray *accounts = [accountStore accountsWithAccountType:facebookTypeAccount];
            facebookAccount = [accounts lastObject];
            //NSLog(@"Success");

            NSURL *meurl = [NSURL URLWithString:@"https://graph.facebook.com/me"];
            SLRequest *merequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
                requestMethod:SLRequestMethodGET
                URL:meurl
                parameters:nil];
            merequest.account = facebookAccount;
            [merequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
                NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
                //this json conaints the log i write above
        }

];

所以我试图从iPhone设置中的Facebook帐户注销,然后再次登录,所以我的问题是每次应用程序打开时都有一种方法可以自动刷新此令牌以避免此问题吗?

1 个答案:

答案 0 :(得分:4)

您无法自动",刷新访问令牌。每当您收到响应时,您应该检查错误,如果存在错误,则更新令牌。此代码可以帮助您 -

....
if([json.profileDictionary objectForKey:@"error"]!=nil){
   [self renewCredentials]; 
}

-(void)renewCredentials{
    [self.accountStore renewCredentialsForAccount:(ACAccount *)self.facebookAccount completion:^(ACAccountCredentialRenewResult renewResult, NSError *error){
        if(!error){
            switch (renewResult) {
                case ACAccountCredentialRenewResultRenewed:
                    NSLog(@"Good to go");
                    [self getFacebookAccount];
                    break;
                case ACAccountCredentialRenewResultRejected:
                    NSLog(@"User declined permission");
                    break;
                case ACAccountCredentialRenewResultFailed:
                    NSLog(@"non-user-initiated cancel, you may attempt to retry");
                    break;
                default:
                    break;
            }
        }
        else{
            //handle error
            NSLog(@"error from renew credentials%@",error);
        }
    }];
}

希望有所帮助!