2013-03-19 21 views
6

我通過Accounts Framework集成了Facebook,我搜索並獲得了一些方法來執行此操作。這是第一次工作,但後來顯示在日誌下面,沒有提供任何信息。Facebook在ios6中獲取用戶信息:必須使用活動訪問令牌來查詢

登錄:

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

任何線索朋友什麼錯誤...謝謝。

回答

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

} 

This one helped me a lot.

+0

「self.facebookAccount」是指什麼? – 2013-06-20 10:49:02

+0

ACAccount * facebookAccount; – BhushanVU 2013-06-20 14:37:33

+0

@bhuXan,很好的答案!但爲什麼我無法獲取用戶的照片? – user1673099 2013-12-05 11:35:58

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 
              }]; 
+0

及其與新創建令牌發生也... – BhushanVU 2013-03-19 06:31:51

+0

於iOS 6..using帳戶編輯答案檢查 – Vinodh 2013-03-19 06:37:27

+1

frmwrk – BhushanVU 2013-03-19 06:46:22

1

請給你的代碼的詳細信息...代碼似乎沒有session..you必須有一個有效的session..and是的accessToken獨特每個用戶ID ..在你的情況下,我認爲會議不在那裏..它可以知道你的訪問令牌。所以,你得到這個錯誤...如果你想知道更多關於訪問令牌..檢查facebook演示項目這是與sdk ..你也可以通過這.. http://developers.facebook.com/docs/concepts/login/access-tokens-and-types/

+0

那它需要訪問的用戶信息在iOS 6中的Facebook的代碼。使用帳戶框架... – BhushanVU 2013-03-19 06:32:42

+1

@bhuXan k..then我想可能是您的訪問令牌由於某種原因會過期..顯示您的整個代碼.. – Shivaay 2013-03-19 06:34:41

+0

多數民衆贊成在整個代碼....我添加了代碼裏面一個按鈕的IBAction .. – BhushanVU 2013-03-19 07:03:40

相關問題