【问题标题】:Fetching user details from Facebook in iOS在 iOS 中从 Facebook 获取用户详细信息
【发布时间】:2013-05-20 17:38:06
【问题描述】:

我是 iPhone 开发的新手。我正在做一个应用程序,其中用户通过 Facebook 进行了 2 次登录,一旦他提交了他的凭据并点击了登录按钮,我必须从 Facebook 获取名字、电子邮件和性别等详细信息,并且在获取用户之后必须被引导到应用程序的注册页面填写详细信息,我需要此应用程序与 iPhone 4,4s 和 5 兼容。

我尝试使用 Facebook Graph API 执行此操作,但无法获得,因此任何人都可以帮助我。

提前致谢。

【问题讨论】:

  • 欢迎来到 SO。您需要发布您尝试过的内容。我们会尽力为您提供帮助,但前提是您已经证明您至少付出了一些努力。

标签: iphone ios objective-c facebook


【解决方案1】:
【解决方案2】:

使用 FBConnect API 获取用户信息。它易于使用

Fbconnect API

希望它对你有用:)

【讨论】:

    【解决方案3】:

    您必须使用图形路径来获取用户信息。

    -(void)getEmailId
    { 
     [facebook requestWithGraphPath:@"me" andDelegate:self];
    }
    
    - (void)openSession
    {
     if (internetActive) {
      NSArray *permissions=[NSArray arrayWithObjects:@"read_stream",@"email",nil];
    
      [FBSession openActiveSessionWithReadPermissions:permissions allowLoginUI:YES completionHandler:
       ^(FBSession *session,
       FBSessionState state, NSError *error) {
       [self sessionStateChanged:session state:state error:error];
      }];
     }else
     {
      UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:@"Internet Not Connected" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
      [alert show];
     }
    }
    
    #pragma mark- request delegate methods 
    
    - (void)request:(FBRequest *)request didLoad:(id)result
    {
      NSLog(@"request did load successfully....");
    
    //  __block NSDictionary *dictionary=[[NSDictionary alloc] init];
    
     if ([result isKindOfClass:[NSDictionary class]]) {
      NSDictionary* json = result;
    
      NSLog(@"email id is %@",[json valueForKey:@"email"]);
      NSLog(@"json is %@",json);
    
      [[NSUserDefaults standardUserDefaults] setValue:[json valueForKey:@"email"] forKey:@"fbemail"];
      [self.viewController login:YES];
     }
    }
    
    - (void)request:(FBRequest *)request didFailWithError:(NSError *)error
    {
     UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"" message:@"Server not responding.." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
    
     [alertView show];
    
     [self fblogout];
     [self showLoginView];
     NSLog(@"request did fail with error");
    }
    
    
    - (void)sessionStateChanged:(FBSession *)session
                          state:(FBSessionState) state
                          error:(NSError *)error
    {
     switch (state) {
      case FBSessionStateOpen: {
          //state open action
      }
    
       // Initiate a Facebook instance
       facebook = [[Facebook alloc]
                        initWithAppId:FBSession.activeSession.appID
                        andDelegate:nil];
    
       // Store the Facebook session information
       facebook.accessToken = FBSession.activeSession.accessToken;
       facebook.expirationDate = FBSession.activeSession.expirationDate;
    
       if (![[NSUserDefaults standardUserDefaults] valueForKey:@"fbemail"]) {
        [MBProgressHUD showHUDAddedTo:self.viewController.view animated:YES];
        [self getEmailId];
       }
    
       break;
      case FBSessionStateClosed:
      case FBSessionStateClosedLoginFailed:
       // Once the user has logged in, we want them to
       // be looking at the root view.
       [self.navController popToRootViewControllerAnimated:NO];
    
       [FBSession.activeSession closeAndClearTokenInformation];
       facebook = nil;
    
       [self showLoginView];
       break;
      default:
       break;
     }
    
     [[NSNotificationCenter defaultCenter]
      postNotificationName:FBSessionStateChangedNotification
      object:session];
    
     if (error) {
      UIAlertView *alertView = [[UIAlertView alloc]
                                initWithTitle:@"Error"
                                message:error.localizedDescription
                                delegate:nil
                                cancelButtonTitle:@"OK"
                                otherButtonTitles:nil];
      [alertView show];
     }
    }
    

    【讨论】:

      【解决方案4】:

      您可以使用以下代码来做到这一点:

      [FBSession openActiveSessionWithReadPermissions:@[@"email",@"user_location",@"user_birthday",@"user_hometown"]
                                         allowLoginUI:YES
                                    completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
      
                                        switch (state) {
                                            case FBSessionStateOpen:
                                                [[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);
                                                        NSLog(@"FB user location:%@",user.location);
                                                        NSLog(@"FB user username:%@",user.username);
                                                        NSLog(@"FB user gender:%@",[user objectForKey:@"gender"]);
                                                        NSLog(@"email id:%@",[user objectForKey:@"email"]);
                                                        NSLog(@"location:%@", [NSString stringWithFormat:@"Location: %@\n\n",
                                                                               user.location[@"name"]]);
      
                                                    }
                                                }];
                                                break;
      
                                            case FBSessionStateClosed:
                                            case FBSessionStateClosedLoginFailed:
                                                [FBSession.activeSession closeAndClearTokenInformation];
                                                break;
      
                                            default:
                                                break;
                                        }
      
                                    } ];
      

      别忘了在你的代码中导入FacebookSDK/FacebookSDK.h

      编辑:Facebook SDK v4 更新(2015 年 4 月 23 日)

      现在,Facebook 发布了新的 SDK,并进行了重大更改。其中不推荐使用 FBSession 类。因此建议所有用户迁移到新的 sdk 和 API。

      下面我已经提到,我们如何通过 Facebook SDK v4 获取用户详细信息:

      if ([FBSDKAccessToken currentAccessToken]) {
      [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:nil]
      startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
        if (!error) {
           NSLog(@”fetched user:%@”, result);
        }
       }];
      }
      

      但在获取用户详细信息之前,我们必须在代码中集成新的 Facebook 登录信息,如 Documentation here 中所述。

      Here 是 SDK v4 的变更日志。我建议通过它进行更新。

      【讨论】:

      • 如何获取用户电话号码?
      • 总是进入 FBSessionStateClosedLoginFailed... 为什么...?
      • @RamaniAshish :可能是由于权限问题。为了完成 Facebook 集成,我们必须在 FB 开发人员中有一个可以工作的应用程序。当我们尝试使用用户帐户详细信息时,他必须提供访问其详细信息的权限。确保所有这些事情都完美地发生。这应该适用于包括我在内的许多其他人:)
      • 使用/me 并填写parameters 归档{ @"fields": @"id,name,email"}
      【解决方案5】:
      FBRequest *request = [FBRequest requestForMe];
      [request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
          if (!error) {
              // handle successful response
          } else if ([error.userInfo[FBErrorParsedJSONResponseKey][@"body"][@"error"][@"type"] isEqualToString:@"OAuthException"]) { // Since the request failed, we can check if it was due to an invalid session
              NSLog(@"The facebook session was invalidated");
              [self logoutButtonTouchHandler:nil];
          } else {
              NSLog(@"Some other error: %@", error);
          }
      }];
      

      【讨论】:

        【解决方案6】:

        添加 info.plist 文件:

          - (IBAction)btn_fb:(id)sender
            {
              if (!FBSession.activeSession.isOpen)
                    {
                        NSArray *_fbPermissions =    @[@"email",@"publish_actions",@"public_profile",@"user_hometown",@"user_birthday",@"user_about_me",@"user_friends",@"user_photos",];
        
                [FBSession openActiveSessionWithReadPermissions:_fbPermissions allowLoginUI:YES completionHandler:^(FBSession *session,FBSessionState state, NSError *error)
                 {
                     if (error)
                     {
                         UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                         [alertView show];
                     }
                     else if(session.isOpen)
                     {
                         [self btn_fb:sender];
                     }
        
        
                 }];
        
        
                return;
            }
        
        
            [FBRequestConnection startWithGraphPath:@"me" parameters:[NSDictionary dictionaryWithObject:@"cover,picture.type(large),id,name,first_name,last_name,gender,birthday,email,location,hometown,bio,photos" forKey:@"fields"] HTTPMethod:@"GET" completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
             {
                 {
                     if (!error)
                     {
                         if ([result isKindOfClass:[NSDictionary class]])
                         {
                             NSLog(@"%@",result);
        
                         }
                     }
                 }
             }];
        }
        

        【讨论】:

          【解决方案7】:

          Facebook 目前已将其 SDK 版本更新为 4.x。要获取用户的个人资料信息,您需要在登录成功后显式调用图形 API(请求所需权限)。

          FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
              initWithGraphPath:@"/me"
                     parameters:@{ @"fields": @"id,name,email"}
                     HTTPMethod:@"GET"];
          [request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
              // Insert your code here
          }];
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多