简体   繁体   English

如何在ios中获取Facebook用户信息

[英]How to fetch Facebook user information in ios

I am trying to develop a simple app, which, retrieves data from Facebook, when the user connects to it. 我正在尝试开发一个简单的应用程序,当用户连接到Facebook时可以从Facebook检索数据。 I tried this code for it. 我试过这个代码。

NSArray *permissions = [[NSArray alloc] initWithObjects:@"user_birthday",@"user_hometown",@"user_location",@"email",@"basic_info", nil];

    [FBSession openActiveSessionWithReadPermissions:permissions
                                       allowLoginUI:YES
                                  completionHandler:^(FBSession *session,
                                                      FBSessionState status,
                                                      NSError *error) {
                                  }];

    [FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
        NSLog(@"%@", [result objectForKey:@"gender"]);
        NSLog(@"%@", [result objectForKey:@"hometown"]);
        NSLog(@"%@", [result objectForKey:@"birthday"]);
        NSLog(@"%@", [result objectForKey:@"email"]);
    }];

But when I run this code, it gives an error "FBSDKLog: Error for request to endpoint 'me': An open FBSession must be specified for calls to this endpoint." 但是当我运行这段代码时,它会给出一个错误“FBSDKLog:对端点请求的错误'我':必须为这个端点的调用指定一个开放的FBSession。”

Thanks in advance, really appreciate your help. 在此先感谢,非常感谢您的帮助。

The error is very appropriate, what it is trying to say is that request connection method should be called once the session is open. 错误是非常合适的,它试图说的是一旦会话打开就应该调用请求连接方法。 Now your 现在你的

[FBSession openActiveSessionWithReadPermissions:permissions
                                   allowLoginUI:YES
                              completionHandler:^(FBSession *session,
                                                  FBSessionState status,
                                                  NSError *error) {
                              }];

method returns BOOL value true or false to specify you wether session is open or not(it tries to open synchronously). 方法返回BOOL值true或false以指定您是否打开会话(它尝试同步打开)。 So first check the result of this call and the put it inside the code for fetching info. 因此,首先检查此调用的结果,并将其放入代码中以获取信息。 For eg. 例如。

 if (FBSession.activeSession.isOpen)
{
[FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
    NSLog(@"%@", [result objectForKey:@"gender"]);
    NSLog(@"%@", [result objectForKey:@"hometown"]);
    NSLog(@"%@", [result objectForKey:@"birthday"]);
    NSLog(@"%@", [result objectForKey:@"email"]);
}];

}

This should remove your error, but you still may not get the results.You may or may not get result on the very first call to this code but whenever the code for completion handler will be called, this method FBRequestConnection will also get called and at that time you'll get the results as it is an asynchronous call. 这应该删除你的错误,但你仍然可能无法得到结果。你可能会或可能不会在第一次调用此代码时获得结果,但每当调用完成处理程序的代码时,此方法FBRequestConnection也将被调用,并且那个时候你会得到结果,因为它是异步调用。

If it still doesn't work try this 如果它仍然无法运行试试这个

 if (FBSession.activeSession.isOpen)
    {
        [[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
            if (error)
            {
                NSLog(@"error:%@",error);

            }
            else
            {
                // retrive user's details at here as shown below
                NSLog(@"FB user first name:%@",user.first_name);
                NSLog(@"FB user last name:%@",user.last_name);
                NSLog(@"FB user birthday:%@",user.birthday);
            }
}];

`(void)fbAccountConfigureWithBlock:(void (^)(id, NSString *))block { _block_data=block; `(void)fbAccountConfigureWithBlock:(void(^)(id,NSString *))block {_block_data = block;

if(![SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook])
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self showAlertMessage:@"" message:@"Please go to settings and add at least one facebook account."];
        _block_data(nil,nil);
    });
    return;
}

ACAccountStore *store = [[ACAccountStore alloc]init];
ACAccountType *accountType = [store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];

[store requestAccessToAccountsWithType:accountType
                               options:@{ACFacebookAppIdKey         : FacebookAppId,
                                         ACFacebookAudienceKey      : ACFacebookAudienceFriends,
                                         ACFacebookPermissionsKey   : @[@"email"]}
                            completion:^(BOOL granted, NSError *error)
 {
     if(granted){
         NSArray *array = [store accountsWithAccountType:accountType];
         if(!array.count){
             dispatch_sync(dispatch_get_main_queue(), ^{
                 [self showAlertMessage:@"" message:@"Please go to settings and add at least one facebook account."];
                 _block_data(nil,nil);
             });
         }
         else{
             ACAccount *account = array[0];
             SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
                                                     requestMethod:SLRequestMethodGET
                                                               URL:[NSURL URLWithString:@"https://graph.facebook.com/me"]
                                                        parameters: @{@"fields":@"id,first_name,last_name,name,email,picture.height(180).width(180)"}];
             [request setAccount:account];

             [request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
              {
                  if(!error){
                      NSDictionary *userData = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
                      NSLog(@"Facebook user data ----> %@",userData);
                      dispatch_async(dispatch_get_main_queue(), ^{
                          if(userData[@"error"] != nil)
                              [self attemptRenewCredentials:store account:account];
                          else
                              _block_data(userData,nil);
                      });
                  }
                  else{
                      dispatch_async(dispatch_get_main_queue(), ^{
                          [self showAlertMessage:@"" message:error.localizedDescription];
                          _block_data(nil,nil);
                      });
                  }
              }];
         }
     }
     else
     {
         dispatch_async(dispatch_get_main_queue(), ^{
             [self showAlertMessage:@"" message:@"We need permission to access your facebook account in order make registration."];
             _block_data(nil,nil);
         });
     }
 }];

}` }`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM