iOS Facebook get user's e-mail

我们两清 提交于 2019-12-06 09:47:54

问题


I tried over 2000 things to get the user's email. I can't get it from the Facebook SDK's graph API. It doesn't contain email property. I also tried to add manually the email property to the FB framework and nothing happened. Is it possible to download the first FB SDK which is compatible with iOS 7? Does it still have the email property, doesn't it? Or is there any other way how to get the REAL email, I must work with them. I don't need the example@facebook.com.

Thanks for any advice.

EDIT

NSArray *permissions = @[@"email", @"public_profile"];
    [PFFacebookUtils logInWithPermissions:permissions block:^(PFUser *user, NSError *error) {
        if (!user) {
            if (!error) {
                NSLog(@"The user cancelled the Facebook login.");
            } else {
                NSLog(@"An error occurred: %@", error.localizedDescription);
            }


            if ([delegate respondsToSelector:@selector(commsDidLogin:)]) {
                [delegate commsDidLogin:NO];
            }
        } else {
            if (user.isNew) {
                NSLog(@"User signed up and logged in through Facebook!");
            } else {
                NSLog(@"User logged in through Facebook!");
            }

            [FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
                if (!error) {
                    PFUser *usere = [PFUser currentUser];
                    [usere setObject:[result objectForKey:@"first_name"] forKey:@"name"];
                    [usere setObject:[result objectForKey:@"last_name"] forKey:@"surname"];
                 //   [usere setObject:[result objectForKey:@"email"] forKey:@"mail"];
                    [usere saveEventually];
                     NSLog(@"user info: %@", result);
                        }
            }];

                }
                if ([delegate respondsToSelector:@selector(commsDidLogin:)]) {
                    [delegate commsDidLogin:YES];
                }
            }];
        }

回答1:


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



回答2:


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




回答3:


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.




回答4:


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




回答5:


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

                     }
                 }];
            }

        }


来源:https://stackoverflow.com/questions/24890798/ios-facebook-get-users-e-mail

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