iOS Facebook get user's e-mail

♀尐吖头ヾ 提交于 2019-12-04 19:23:27

I have not code for graph API,

but with new facebook sdk version 3, I have code for that.

-(void)openFbSession
{
    [[self appDelegate].session closeAndClearTokenInformation];

    NSArray *permissions =     [NSArray arrayWithObjects:@"email",@"user_location",@"user_birthday",@"user_hometown",nil];
    [self appDelegate].session = [[FBSession alloc] initWithPermissions:permissions];

    [[self appDelegate].session openWithCompletionHandler:^(FBSession *session,
                                                            FBSessionState status,
                                                            NSError *error) {
        if(!error)
        {
            NSLog(@"success");
            [self myFbInfo];
        }
        else
        {
            NSLog(@"failure");
        }

    }];
}

and for all information, myFbInfo method is

-(void)myFbInfo
{
    [FBSession setActiveSession:[self appDelegate].session];

    [[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *FBuser, NSError *error) {
        if (error) {
            // Handle error
        }

        else {
            //NSString *userName = [FBuser name];
            //NSString *userImageURL = [NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?type=large", [FBuser id]];
            NSLog(@"Name : %@",[FBuser name]);
            NSLog(@"first name : %@",[FBuser first_name]);
            NSLog(@"Last name : %@",[FBuser last_name]);
            NSLog(@"ID : %@",[FBuser id]);
            NSLog(@"username : %@",[FBuser username]);
            NSLog(@"Email : %@",[FBuser objectForKey:@"email"]);

            NSLog(@"user all info : %@",FBuser);

              }
    }];

}

EDIT


in appdelegate.h

@property (strong, nonatomic) FBSession *session;

in appdelegate.m

- (BOOL)application: (UIApplication *)application openURL: (NSURL *)url sourceApplication: (NSString *)sourceApplication annotation: (id)annotation
{
    //NSLog(@"FB or Linkedin clicked");
    return [self.session handleOpenURL:url];
}


- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [FBSession.activeSession handleDidBecomeActive];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    [self.session close];
}

You have to request permissions first, as descibed at https://developers.facebook.com/docs/facebook-login/ios/v2.0#button-permissions

After that, you can request the user's information: https://developers.facebook.com/docs/ios/graph#userinfo

You can't just get the user's email address, you must ask them for permission to do so. Take a look at this:
https://developers.facebook.com/docs/facebook-login/permissions/v2.0

Facebook Connect will allow the passing of scope=email in the get string of your auth call.

I could not get it to work with above examples. I solved it using a more complex call to FBSDKGraphRequest..

In viewDidLoad:

if(FBSDKAccessToken.currentAccessToken() != nil) {

  println("Logged in to FB")
  self.returnUserData()  //Specified here below

} else {
  print("Not logged in to FB")

  let loginView : FBSDKLoginButton = FBSDKLoginButton()
  loginView.center = self.view.center
  loginView.readPermissions = ["public_profile", "email", "user_friends"]
  loginView.delegate = self
  self.view.addSubview(loginView)
  }
}

Read permissions above is important to be able to get it later on when you request from FB server.

Remember to conform to the "FBSDKLoginButtonDelegate" protocols by including the functions needed (not included here).

To be able to fetch email etc. I use the more complex call for the graphRequest and specify the accesstoken and the parameters (se below).

 let fbAccessToken = FBSDKAccessToken.currentAccessToken().tokenString   

    let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(
    graphPath: "me", 
    parameters: ["fields":"email,name"], 
    tokenString: fbAccessToken, 
    version: nil, 
    HTTPMethod: "GET")

... and in the same function execute with completionHandler:

graphRequest.startWithCompletionHandler({ (connection, result, error) -> () in result

  if ((error) != nil) {
    // Process error
    println("Error: \(error)")
  } else {
    println("fetched user: \(result)")
  }
}

Works beautifully!

And additionally.. parameters are found listed here:

https://developers.facebook.com/docs/graph-api/reference/v2.2/user

        if ([result.grantedPermissions containsObject:@"email"]) {
            // Do work
            NSLog(@"%@",[FBSDKAccessToken currentAccessToken]);

            if ([FBSDKAccessToken currentAccessToken]) {
                [[[FBSDKGraphRequest alloc] initWithGraphPath:@"/me" parameters:[NSMutableDictionary dictionaryWithObject:@"picture.type(large),id,email,name,gender" forKey:@"fields"] tokenString:result.token.tokenString version:nil HTTPMethod:@"GET"]
                 startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
                     if (!error) {

                         NSLog(@"fetched user:%@", result);

                     }
                 }];
            }

        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!