14

I'm trying to get information through the facebook sdk but so far I'm getting only the id and the name of the user, although I'm sure there is an email available, as it is my account. I've been looking at several answer here but none of them solved my problem so far. What am I doing wrong, and why is it not returning more data as I am requesting several permissions?

Here is my code:

fbLoginManager.logInWithReadPermissions(["public_profile", "email", "user_friends", "user_about_me", "user_birthday"], handler: { (result, error) -> Void in
        if ((error) != nil)
        {
            // Process error
            println("There were an error: \(error)")
        }
        else if result.isCancelled {
            // Handle cancellations
            fbLoginManager.logOut()
        }
        else {
            var fbloginresult : FBSDKLoginManagerLoginResult = result
            if(fbloginresult.grantedPermissions.contains("email"))
            {
                println(fbloginresult)
                self.returnUserData()
            }
        }
    })

And the function to get the user data:

func returnUserData()
{
    let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
    graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in

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

            if let userName : NSString = result.valueForKey("name") as? NSString {
                println("User Name is: \(userName)")
            }
            if let userEmail : NSString = result.valueForKey("email") as? NSString {
                println("User Email is: \(userEmail)")
            }
        }
    })
}

Which returns:

fetched user: {
id = 55555555;
name = "Kali Aney";
}
User Name is: Kali Aney
Suhaib
  • 2,031
  • 3
  • 24
  • 36
Kalianey
  • 2,738
  • 6
  • 25
  • 43

9 Answers9

38

Facebook Graph API broke it’s backward compatibility (when used in a default fashion) Since Graph-API version 2.4 (Pod Version 4.4.0).

FB Graph-API 2.4 does NOT return all default fields for user

To resolve this you can either use explicitly graph version 2.3:

[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:nil tokenString:[FBSDKAccessToken currentAccessToken].tokenString version:@"v2.3" HTTPMethod:nil]

in which case FB assures v2.3 will be available at least 2 years from now. https://developers.facebook.com/docs/graph-api/overview:

The Graph API has multiple versions available to access at any one time. Each version contains a set ofcore fields and edge operations. We make a guarantee that those core APIs will be available and un-modified in that version for at least 2 years from release. The platform changelog can tell you which versions are currently available.

OR

you can use new Graph-API (v2.4) in by asking for specific fields you are interested in:

[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:@{@"fields" : @"email,name"}]

gmaliar
  • 5,294
  • 1
  • 28
  • 36
HeTzi
  • 916
  • 9
  • 18
  • with Graph-API 2.4, how to get logged in user's birthday or what to pass in the @"fields" for birthday? – Nirmit Dagly Sep 02 '15 at 13:00
  • Great surprise from FB, and @HeTzi thanks for the answer – Evgeny Karkan Dec 18 '15 at 14:21
  • Already there. Giving for App but for Browser. It's not returning email – Saad Dec 02 '16 at 12:17
  • 2
    Since this is the first answer that comes up on google search, I think you should add that you don't get email for users that haven't verified their email and **only** for users that have done the verification. – Rikh Mar 30 '17 at 15:58
  • I'm still not able to get my email even after specifying `@{@"fields" : @"email,name"}`. This was working last week. My case seems like a separate issue. – Genki Feb 14 '18 at 20:45
  • it didn't help me but I have figured out that I was missing required permission `email` and I was only requesting `public_profile`. Make sure you have right permissions – Yusuf Kamil AK May 07 '18 at 13:31
  • I have tried both ways, but can't seem to get "email" field, any update on this? – Mohsin Khubaib Ahmed Mar 04 '19 at 09:01
8

I struggled with this problem for almost a day until finding the answer by @HeTzi, which worked perfectly. The swift version of such a request is:

func referenceFBData() {
    var request = FBSDKGraphRequest(graphPath:"me", parameters: ["fields":"email,first_name,gender"]);

    request.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in
        if error == nil {
            println("The information requested is : \(result)")
        } else {
            println("Error getting information \(error)");
        }
    }
}

Remember that you must first request the proper read permissions to obtain data using this request.

Trey Pringle
  • 131
  • 5
8

In my case email was not verified by the user thats why not getting it even after granting the permissions ;)

Ammar Mujeeb
  • 1,222
  • 18
  • 21
  • How did you came to know that this was the issue, as Fb is not throwing any such errors ? – Mr. Bean Apr 18 '17 at 06:10
  • I dont remember clearly but i think i was using test users without granting the email permission explicitly then when i use my personal account, got the email in response then i came to know the actual reason. – Ammar Mujeeb Apr 18 '17 at 11:28
5

this works... hope it helps..

NSMutableDictionary* parameters = [NSMutableDictionary dictionary];
    [parameters setValue:@"id, name, email" forKey:@"fields"];

    [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:parameters]
     startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) 
{
         NSLog(@"Fetched user is:%@", result);
}];
1

A function in swift like this:

func fbsignup() {
        let lgManager = FBSDKLoginManager()
        lgManager.logInWithReadPermissions(["public_profile","email"], fromViewController: self,handler: { (result:FBSDKLoginManagerLoginResult!, error:NSError!) -> Void in
            if error != nil{
                print("facebook error")
            }else if result.isCancelled {
                print("Canceled")
            }else{
                if result.grantedPermissions.contains("email") {
                    if (FBSDKAccessToken.currentAccessToken() != nil) {
                        FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"email,name"]) .startWithCompletionHandler({ (connection:FBSDKGraphRequestConnection!, result:AnyObject!, error:NSError!) -> Void in
                            print(result)
                        })
                    }
                }
            }
        })
    }
William Hu
  • 15,423
  • 11
  • 100
  • 121
1

Tested in Swift 2.2

func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
        print("User Logged In")
if ((error) != nil)
        {
            // Process error
        }
        else if result.isCancelled {
            // Handle cancellations
        }
        else {
            // If you ask for multiple permissions at once, you
            // should check if specific permissions missing
            if result.grantedPermissions.contains("email")
            {
                // Do work
                getUserData()
            }
        }}

func getUserData()
{
    if ((FBSDKAccessToken.currentAccessToken()) != nil)
    {
        let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "email, name"])
        graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in

            if ((error) != nil)
            {
                // Process error
                print("Error: \(error)")
            }
            else
            {
                print("fetched user: \(result)")
                let userName : NSString = result.valueForKey("name") as! NSString
                print("User Name is: \(userName)")
                let userEmail : NSString = result.valueForKey("email") as! NSString
                print("User Email is: \(userEmail)")

            }
        })
    }
}
karthikPrabhu Alagu
  • 3,371
  • 1
  • 21
  • 25
1

Use these functions this will work for sure

@IBAction func fbsignup(_ sender: Any) {
        let fbloginManger: FBSDKLoginManager = FBSDKLoginManager()
        fbloginManger.logIn(withReadPermissions: ["email"], from:self) { (result, error) -> Void in
            if(error == nil){
                let fbLoginResult: FBSDKLoginManagerLoginResult  = result!

                if( result?.isCancelled)!{
                    return }


                if(fbLoginResult .grantedPermissions.contains("email")){
                    self.getFbId()
                }
            }  }

    }
    func getFbId(){
    if(FBSDKAccessToken.current() != nil){
    FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id,name , first_name, last_name , email"]).start(completionHandler: { (connection, result, error) in
    if(error == nil){
    print("result")
    }
    })
    }
    }

and connect the fbsignup(_sender: Any) function with your button

Yaseen Ahmad
  • 1,807
  • 5
  • 25
  • 43
Ayush Dixit
  • 467
  • 4
  • 10
1

Enable your email access in Facebook Developer site

https://developers.facebook.com/apps/app-review/permissions/

Go to Facebook Developer site-> click App Review-> Check Permissions and Features-> Change Standard Access to Advanced Access

check imageenter image description here

https://developers.facebook.com/search/?q=apps%20app%20review%20permissions&notfound=1

0

I have never worked with IOS, but I have a lot of experience with Facebook. My first observation is that whenever you request a Facebook permission, you must make sure that: - you let your users know why you need that permission - you respect Facebook's terms - you will surely need that permission in the near future

This list

["public_profile", "email", "user_friends", "user_about_me", "user_birthday"]

seems to be vague. You must make sure that you request for the minimal set of privileges you will surely need in the near future.

As about the request itself, you must make sure that you use a valid Facebook session. I do it like this in PHP:

        $request = new \Facebook\FacebookRequest( self::$session, 'GET', '/me' );
        $response = $request->execute();
        // get response
        $graphObject = $response->getGraphObject()->asArray();

I am sure you must have something like getGraphObject in your SDK as well.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • Thank you for your answer, but I'm not sure how to use it for iOS... I'm requesting the email permission, so this one should be there in the return. – Kalianey Jul 16 '15 at 09:03