6

我正在通过 Accounts Framework 集成 facebook,我搜索并获得了一些方法来做到这一点。它第一次工作,但后来它显示在日志下面并且没有提供任何信息。

日志:

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

我使用的代码

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);
                                            }
                                        }];

任何线索朋友出了什么问题...谢谢。

4

3 回答 3

14

问题是,当我更改设备内的 facebook 设置时,访问令牌超时。因此,如果您侦听 ACAccountStoreDidChangeNotification,则可以调用 renewCredentialsForAccount: 来提示用户获得许可。

下面的代码正在工作并在字典中获取用户信息。

- (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) {}];

}

这对我帮助很大。

于 2013-03-19T13:17:10.523 回答
1

你需要创建会话

 [FBSession openActiveSessionWithReadPermissions:permissions
                                           allowLoginUI:YES
                                      completionHandler:^(FBSession *session, FBSessionState status, NSError *error){
                                          if (session.isOpen) {
                                              switch (status) {
                                                  case FBSessionStateOpen:
                                                          // here you get the token
                                                          NSLog(@"%@", session.accessToken);
                                                      break;
                                                  case FBSessionStateClosed:
                                                  case FBSessionStateClosedLoginFailed:
                                                      [[FBSession activeSession] closeAndClearTokenInformation];
                                                      break;
                                                  default:
                                                      break;
                                              } // switch
                                          }];
于 2013-03-19T06:22:39.727 回答
1

请提供您的代码的更多详细信息...您的代码似乎没有会话..您必须有一个有效的会话..每个用户 ID 的 accessToken 都是唯一的..在您的情况下,我认为会话不存在。 .它如何知道您的访问令牌..所以,您收到此错误...如果您想了解有关访问令牌的更多信息..检查带有sdk的facebook演示项目..您也可以通过这个.. http ://developers.facebook.com/docs/concepts/login/access-tokens-and-types/

于 2013-03-19T06:25:13.583 回答