Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Facebook Get User Info in ios6 :An active access token must be used to query

I am integrating facebook through Accounts Framework, I searched and got some ways to do it. It was working first time but later it showing below log and not giving any information.

Log:

Dictionary contains: {
    error =     {
        code = 2500;
        message = "An active access token must be used to query information about the current user.";
        type = OAuthException;
    };
}

Code i used

ACAccountStore *_accountStore=[[ACAccountStore alloc] init];;
    ACAccountType *facebookAccountType = [_accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];

    // We will pass this dictionary in the next method. It should contain your Facebook App ID key,
    // permissions and (optionally) the ACFacebookAudienceKey
    NSArray * permissions = @[@"email"];

    NSDictionary *options = @{ACFacebookAppIdKey :@"my app id",
    ACFacebookPermissionsKey :permissions,
    ACFacebookAudienceKey:ACFacebookAudienceFriends};

    // Request access to the Facebook account.
    // The user will see an alert view when you perform this method.
    [_accountStore requestAccessToAccountsWithType:facebookAccountType
                                           options:options
                                        completion:^(BOOL granted, NSError *error) {
                                            if (granted)
                                            {
                                                // At this point we can assume that we have access to the Facebook account
                                                NSArray *accounts = [_accountStore accountsWithAccountType:facebookAccountType];

                                                // Optionally save the account
                                                [_accountStore saveAccount:[accounts lastObject] withCompletionHandler:nil];

                                                //NSString *uid = [NSString stringWithFormat:@"%@", [[_accountStore valueForKey:@"properties"] valueForKey:@"uid"]] ;
                                                NSURL *requestURL = [NSURL URLWithString:[@"https://graph.facebook.com" stringByAppendingPathComponent:@"me"]];

                                                SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
                                                                                        requestMethod:SLRequestMethodGET
                                                                                                  URL:requestURL
                                                                                           parameters:nil];
                                                request.account = [accounts lastObject];
                                                [request performRequestWithHandler:^(NSData *data,
                                                                                     NSHTTPURLResponse *response,
                                                                                     NSError *error) {

                                                    if(!error){
                                                        NSDictionary *list =[NSJSONSerialization JSONObjectWithData:data
                                                                                                            options:kNilOptions error:&error];
                                                        NSLog(@"Dictionary contains: %@", list );
                                                        userName=[list objectForKey:@"name"];
                                                        NSLog(@"username %@",userName);

                                                        userEmailID=[list objectForKey:@"email"];
                                                        NSLog(@"userEmailID %@",userEmailID);

                                                        userBirthday=[list objectForKey:@"birthday"];
                                                        NSLog(@"userBirthday %@",userBirthday);

                                                        userLocation=[[list objectForKey:@"location"] objectForKey:@"name"];
                                                        NSLog(@"userLocation %@",userLocation);
                                                    }
                                                    else{
                                                        //handle error gracefully
                                                    }

                                                }];
                                            }
                                            else
                                            {
                                                NSLog(@"Failed to grant access\n%@", error);
                                            }
                                        }];

any clues friends what is going wrong...Thanks.

like image 930
BhushanVU Avatar asked Mar 19 '13 06:03

BhushanVU


2 Answers

The problem was that when I changed my facebook setting inside device the access token got timed out . so if you listen for an ACAccountStoreDidChangeNotification you can then call renewCredentialsForAccount: to prompt the user for permission.

The below code is working and getting user info in a dictionary.

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(accountChanged) name:ACAccountStoreDidChangeNotification object:nil];


}

-(void)getUserInfo
{

self.accountStore = [[ACAccountStore alloc]init];
    ACAccountType *FBaccountType= [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];

    NSString *key = @"your_app_id";
    NSDictionary *dictFB = [NSDictionary dictionaryWithObjectsAndKeys:key,ACFacebookAppIdKey,@[@"email"],ACFacebookPermissionsKey, nil];


    [self.accountStore requestAccessToAccountsWithType:FBaccountType options:dictFB completion:
     ^(BOOL granted, NSError *e) {
         if (granted) {
             NSArray *accounts = [self.accountStore accountsWithAccountType:FBaccountType];
             //it will always be the last object with single sign on
             self.facebookAccount = [accounts lastObject];
             NSLog(@"facebook account =%@",self.facebookAccount);
             [self get];
         } else {
             //Fail gracefully...
             NSLog(@"error getting permission %@",e);

         }
     }];
}


-(void)accountChanged:(NSNotification *)notif//no user info associated with this notif
{
    [self attemptRenewCredentials];
}


-(void)attemptRenewCredentials{
    [self.accountStore renewCredentialsForAccount:(ACAccount *)self.facebookAccount completion:^(ACAccountCredentialRenewResult renewResult, NSError *error){
        if(!error)
        {
            switch (renewResult) {
                case ACAccountCredentialRenewResultRenewed:
                    NSLog(@"Good to go");
                    [self get];
                    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 gracefully

            NSLog(@"error from renew credentials%@",error);

        }

    }];
}

-(void)get
{

    NSURL *requestURL = [NSURL URLWithString:@"https://graph.facebook.com/me"];

    SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
                                            requestMethod:SLRequestMethodGET
                                                      URL:requestURL
                                               parameters:nil];
    request.account = self.facebookAccount;

    [request performRequestWithHandler:^(NSData *data,
                                         NSHTTPURLResponse *response,
                                         NSError *error) {

        if(!error)
        {
           NSDictionary *list =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

            NSLog(@"Dictionary contains: %@", list );
        }
        else{
            //handle error gracefully
            NSLog(@"error from get%@",error);
            //attempt to revalidate credentials
        }

    }];

    self.accountStore = [[ACAccountStore alloc]init];
    ACAccountType *FBaccountType= [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];

    NSString *key = @"your_app_id";
    NSDictionary *dictFB = [NSDictionary dictionaryWithObjectsAndKeys:key,ACFacebookAppIdKey,@[@"friends_videos"],ACFacebookPermissionsKey, nil];


    [self.accountStore requestAccessToAccountsWithType:FBaccountType options:dictFB completion:
     ^(BOOL granted, NSError *e) {}];

}

This one helped me a lot.

like image 119
BhushanVU Avatar answered Nov 03 '22 05:11

BhushanVU


Please give the more details of your code...your code seems to be not having session..you must have a valid session..and the accessToken is unique for each user id..in your case i think session is not there..how it can know your access token..So, you are getting this error...If you want to know more about access token..check facebook demo projects which is with sdk..you can also go through this..http://developers.facebook.com/docs/concepts/login/access-tokens-and-types/

like image 41
Kundan Avatar answered Nov 03 '22 05:11

Kundan