如何获取 Facebook SDK 的用户名和电子邮件 ID?

Posted

技术标签:

【中文标题】如何获取 Facebook SDK 的用户名和电子邮件 ID?【英文标题】:How to get user name and email id for Facebook SDK? 【发布时间】:2014-02-25 09:54:49 【问题描述】:

我用过的代码

 if (FBSession.activeSession.state == FBSessionStateOpen
        || FBSession.activeSession.state == FBSessionStateOpenTokenExtended) 

        // Close the session and remove the access token from the cache
        // The session state handler (in the app delegate) will be called automatically
        [FBSession.activeSession closeAndClearTokenInformation];


        // If the session state is not any of the two "open" states when the button is clicked
     else 
        // Open a session showing the user the login UI
        // You must ALWAYS ask for basic_info permissions when opening a session
        [FBSession openActiveSessionWithReadPermissions:@[@"basic_info,email"]
                                           allowLoginUI:YES
                                      completionHandler:
         ^(FBSession *session, FBSessionState state, NSError *error) 




             // Retrieve the app delegate
             AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
             // Call the app delegate's sessionStateChanged:state:error method to handle session state changes
             [appDelegate sessionStateChanged:session state:state error:error];
         ];
    

我需要从这段代码中获取用户名和邮件 ID。如果有人知道解决方案,请帮助我提前谢谢。

【问题讨论】:

[Facebook-ios-SDK 4.0]How to get user email address from FBSDKProfile的可能重复 【参考方案1】:
  if ([FBSDKAccessToken currentAccessToken]) 
                     [[[FBSDKGraphRequest alloc] initWithGraphpath:@"me" parameters:@@"fields": @"email,name,first_name"]
                      startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) 
                          if (!error) 
                              NSLog(@"fetched user:%@", result);
                               NSLog(@"%@",result[@"email"]);

                          
                      ];


                 

【讨论】:

【参考方案2】:

使用以下代码

 FBSession *session = [[FBSession alloc] initWithPermissions:@[@"basic_info", @"email"]];
    [FBSession setActiveSession:session];

    [session openWithBehavior:FBSessionLoginBehaviorForcingWebView
            completionHandler:^(FBSession *session,
                                FBSessionState status,
                                NSError *error) 
                if (FBSession.activeSession.isOpen) 
                    [[FBRequest requestForMe] startWithCompletionHandler:
                     ^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) 
                         if (!error) 
                              NSLog(@"accesstoken %@",[NSString stringWithFormat:@"%@",session.accessTokenData]);
                             NSLog(@"user id %@",user.id);
                             NSLog(@"Email %@",[user objectForKey:@"email"]);
                             NSLog(@"User Name %@",user.username);
                         
                     ];
                
            ];

【讨论】:

“basic_info”不再可用,您应该使用“public_info”权限。来源:***.com/questions/24762791/…【参考方案3】:

对于新代码 facebook SDK ver 4.0 及更高版本

看到这个link

下面

 //  use facebook SDK 3.8 

在 AppDelegate.m 中添加以下方法

 -(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:  (NSString *)sourceApplication annotation:(id)annotation

return [FBAppCall handleOpenURL:url sourceApplication:sourceApplication  fallbackHandler:^(FBAppCall *call)
        
            NSLog(@"Facebook handler");
        
        ];



- (void)applicationDidBecomeActive:(UIApplication *)application

[FBAppEvents activateApp];
[FBAppCall handleDidBecomeActive];
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.


- (void)applicationWillTerminate:(UIApplication *)application

 [FBSession.activeSession close];
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

查看 viewcontroler .h 中的以下代码

#import <UIKit/UIKit.h>
#import <FacebookSDK/FacebookSDK.h>
#import <CoreLocation/CoreLocation.h>

@interface ViewController : UIViewController<FBLoginViewDelegate>


@property (strong, nonatomic) IBOutlet UILabel *lblUserName;
@property (strong, nonatomic) IBOutlet UITextField *txtEmailId;
@property (strong, nonatomic) IBOutlet UIButton *lblCreate;
@property (strong, nonatomic) IBOutlet FBProfilePictureView *profilePic;

@property (strong, nonatomic) id<FBGraphUser> loggedInUser;

- (IBAction)butCreate:(id)sender;

- (void)showAlert:(NSString *)message
       result:(id)result
        error:(NSError *)error;

@end

// 将以下代码应用到您的视图控制器.m

- (void)viewDidLoad

[super viewDidLoad];
FBLoginView *loginview=[[FBLoginView alloc]initWithReadPermissions:@[@"email",@"user_likes"]];
loginview.frame=CGRectMake(60, 50, 200, 50);
loginview.delegate=self;
[loginview sizeToFit];
[self.view addSubview:loginview];



-(void)loginViewShowingLoggedInUser:(FBLoginView *)loginView

self.lblCreate.enabled=YES;
self.txtEmailId.enabled=YES;
self.lblUserName.enabled=YES;




-(void)loginViewFetchedUserInfo:(FBLoginView *)loginView user:(id<FBGraphUser>)user

self.lblUserName.text=[NSString stringWithFormat:@"%@",user.name];
self.txtEmailId.text=[user objectForKey:@"email"];
//self.profilePic.profileID=user.id;
self.loggedInUser=user;


-(void)loginViewShowingLoggedOutUser:(FBLoginView *)loginView


self.txtEmailId.text=nil;
self.lblUserName.text=nil;
self.loggedInUser=nil;
self.lblCreate.enabled=NO;


-(void)loginView:(FBLoginView *)loginView handleError:(NSError *)error
   NSLog(@"Show the Error ==%@",error);

Swift 1.2 及以上版本

创建字典:

class ViewController: UIViewController 
    var dict : NSDictionary!

获取数据:

if((FBSDKAccessToken.currentAccessToken()) != nil)
    FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).startWithCompletionHandler( (connection, result, error) -> Void in
        if (error == nil)
            self.dict = result as NSDictionary               
            println(self.dict)
            NSLog(self.dict.objectForKey("picture")?.objectForKey("data")?.objectForKey("url") as String)
        
    )

输出应该是:


    email = "karthik.saral@gmail.com";
    "first_name" = Karthi;
    id = 924483474253864;
    "last_name" = keyan;
    name = "karthi keyan";
    picture =     
        data =         
            "is_silhouette" = 0;
            url = "XXXXXXX";
        ;
    ;

【讨论】:

只是我还是这个答案是 Objective-C 和 Swift 的奇怪组合?【参考方案4】:

成功登录后发出以下请求,您没有读取它的publish_actions权限。

/* make the API call */
[FBRequestConnection startWithGraphPath:@"/me"
                             parameters:nil
                             HTTPMethod:@"GET"
                      completionHandler:^(
                          FBRequestConnection *connection,
                          id result,
                          NSError *error
                      ) 
                          /* handle the result */
                      ];

点击此链接:https://developers.facebook.com/docs/graph-api/reference/user

【讨论】:

【参考方案5】:

您可以使用NSDictionary: NSDictionary&lt;FBGraphUser&gt; *user获取这些信息, 您只需要使用objectforkey 来访问这些值,例如:

[user objectForKey:@"id"],

[user objectForKey:@"username"],

[user objectForKey:@"email"].

希望它对你有用。

【讨论】:

【参考方案6】:

这目前适用于最新版本的 FB SDK:

在正确设置FB登录按钮之前的某个地方(假设self.facebookLoginButton是通过IB初始化的):

self.facebookLoginButton.readPermissions = @[@"public_profile", @"email"];
self.facebookLoginButton.delegate = self;

然后在loginButton:didCompleteWithResult:error::

- (void)loginButton:(FBSDKLoginButton *)loginButton
didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result
              error:(NSError *)error

    NSDictionary *parameters = @@"fields":@"email,name";
    FBSDKGraphRequest *graphRequest = [[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:parameters];
    [graphRequest startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error)
    
        LogInfo(@"fetched user:%@", result);
    ];

这里是有帮助的参考页面:https://developers.facebook.com/docs/graph-api/reference/user

【讨论】:

【参考方案7】:

User 对象的用户名字段已被移除,并且在 Graph API v2.0 中不存在。在 API 的 v2.0 中,无法获取用户的 FB 用户名。您可以使用应用范围 ID 作为用户名。

Facebook 删除了用户名,因为用户名是通过 Facebook 发送电子邮件的一种方式。 例如,给定 URL http://www.facebook.com/sebastian.trug 相应的 Facebook 电子邮件是 sebastian.trug@facebook.com 如果通过电子邮件发送,将直接接收到消息(如果消息设置设置为公开),否则将接收到另一个收件箱。

来源:https://developers.facebook.com/docs/apps/changelog#v2_0_graph_api

这里是 swift 3.0 的代码

     let graphRequest:FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", 
    parameters: ["fields":"first_name,email, picture.type(large)"])

            graphRequest.start(completionHandler:  (connection, result, 
          error) -> Void in

                if ((error) != nil)
                
                    print("Error: \(error)")
                
                else
                
                    let data:[String:AnyObject] = result as! [String : AnyObject]
                    print(data)

                
            )

【讨论】:

【参考方案8】:
[FBRequestConnection startWithGraphPath:@"/me"
                             parameters:nil
                             HTTPMethod:@"GET"
                      completionHandler:^(
                                          FBRequestConnection *connection,
                                          NSDictionary *result,
                                          NSError *error
                                          ) 
                          /* handle the result */
                          _fbId = [result objectForKey:@"id"];
                          _fbName = [result objectForKey:@"name"];
                          _fbEmail = [result objectForKey:@"email"];

                          NSLog(@"%@",_fbId);
                          NSLog(@"%@",_fbName);
                          NSLog(@"%@",_fbEmail);
                      ];

【讨论】:

【参考方案9】:

使用此代码:

    FBSession *session = [[FBSession alloc] initWithPermissions:@[@"public_profile"]];
    [FBSession setActiveSession:session];

    [session openWithBehavior:FBSessionLoginBehaviorForcingWebView
            completionHandler:^(FBSession *session,
                                FBSessionState status,
                                NSError *error) 
                if (FBSession.activeSession.isOpen)
                
                    [[FBRequest requestForMe] startWithCompletionHandler:
                     ^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error)
                     
                         if (!error)
                         
                             NSLog(@"%@", user);
                             [[[UIAlertView alloc] initWithTitle:@"welcome"
                                                         message:[NSString stringWithFormat:@"%@\n%@\n%@\n%@\n%@\n%@",
                                                                  user[@"name"],
                                                                  user[@"gender"],
                                                                  user[@"id"],
                                                                  user[@"link"],
                                                                  user[@"email"],
                                                                  user[@"timezone"]]
                                                        delegate:nil
                                               cancelButtonTitle:@"OK"
                                               otherButtonTitles:nil]
                              show];
                         
                     ];
                
            ];

【讨论】:

【参考方案10】:

facebook ios sdk 快速获取用户名和电子邮件 3

 FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, email"]).start(completionHandler:  (connection, result, error) -> Void in
            if (error == nil)
                let fbDetails = result as! NSDictionary
                print(fbDetails)
            else
                print(error?.localizedDescription ?? "Not found")
            
        )

【讨论】:

【参考方案11】:

Xcode 8.2.1 和 Objective-C

杀掉应用后在任何地方获取登录信息

   FBRequest *friendRequest = [FBRequest requestForGraphPath:@"me/?fields=name,picture,birthday,email,location"];
                 [friendRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error)
                  
                      if(error == nil) 

                          UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Facebook" message:@"Success in fetching Facebook information." delegate:self cancelButtonTitle:@"OK"otherButtonTitles:nil, nil];
                          [alert show];

                      
                      else
                      
                          UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Facebook" message:@"Problem in fetching Facebook Information. Try Later!" delegate:self cancelButtonTitle:@"OK"otherButtonTitles:nil, nil];
                          [alert show];
                      


                  ];

【讨论】:

【参考方案12】:
    首先您必须通过 GraphAPI 获得您的应用程序的访问权限。

使用 objectandKey 创建一个 NSMutableDictionary。 您的对象将是您收到的值,例如您的姓名和 emailId。

代码sn-p:

NSMutableDictionary *params=[[NSMutableDictionary alloc]init];

[params setObject:nameStr forKey:@"name"];

[params setObject:emailStr forKey:@"email"];

【讨论】:

以上是关于如何获取 Facebook SDK 的用户名和电子邮件 ID?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Facebook SDK 获取姓名和电子邮件

iOS - Facebook SDK v.4.5.1 - 获取用户名和电子邮件

如何在 iOS 上使用 Facebook SDK 3.1 获取用户的电子邮件?

如何在 Facebook Android sdk 4.0 中使用 Graph Request 获取登录用户的电子邮件地址

Facebook SDK 3.7 for Android 请求电子邮件权限

如何通过 facebook SDK 在 iOS 中获取用户名和密码