14

The code I have used

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

from this code i need to get user name and mail id. if any one know the solution please help me thanks in advance.

Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
Peer Mohamed Thabib
  • 636
  • 2
  • 9
  • 29
  • Possible duplicate of [\[Facebook-iOS-SDK 4.0\]How to get user email address from FBSDKProfile](http://stackoverflow.com/questions/29323244/facebook-ios-sdk-4-0how-to-get-user-email-address-from-fbsdkprofile) – AechoLiu Jan 21 '16 at 06:58

12 Answers12

17
  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"]);

                          }
                      }];


                 }
Myaaoonn
  • 1,001
  • 12
  • 25
12

Use the Following Code

 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);
                         }
                     }];
                }
            }];
iDeveloper
  • 498
  • 4
  • 9
  • 2
    "basic_info" is no longer available, you should use "public_info" permission. Source : http://stackoverflow.com/questions/24762791/facebook-sdk-invalide-scope-basic-info-use-public-profile-user-friends-inst – Paweł Brewczynski Nov 02 '14 at 10:35
3

for new code facebook SDK ver 4.0 and above

see this link

below

 //  use facebook SDK 3.8 

add the following methods in 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:.
}

se the follwing code in your 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

// apply the below code to your view controller.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 & above

Create a dictionary :

class ViewController: UIViewController {
    var dict : NSDictionary!
}

Fetching the data :

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

Output should be :

{
    email = "karthik.saral@gmail.com";
    "first_name" = Karthi;
    id = 924483474253864;
    "last_name" = keyan;
    name = "karthi keyan";
    picture =     {
        data =         {
            "is_silhouette" = 0;
            url = "XXXXXXX";
        };
    };
}
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
1

Make the following request after successfully login in, you don't read publish_actions permissions for it.

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

follow this link: https://developers.facebook.com/docs/graph-api/reference/user

Basheer_CAD
  • 4,908
  • 24
  • 36
1

You can get these information by using the NSDictionary: NSDictionary<FBGraphUser> *user, you just need to use objectforkey to access these values like :

[user objectForKey:@"id"],

[user objectForKey:@"username"],

[user objectForKey:@"email"].

Hopefully it will work for you.

Sport
  • 8,570
  • 6
  • 46
  • 65
Irfan
  • 4,301
  • 6
  • 29
  • 46
1

This currently works with the latest version of the FB SDK:

Somewhere before set up the FB login button correctly (assuming self.facebookLoginButton is initialized via IB):

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

Then in 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);
    }];
}

Here is the reference page that helped: https://developers.facebook.com/docs/graph-api/reference/user

Stunner
  • 12,025
  • 12
  • 86
  • 145
1

The username field of the User object has been removed, and does not exist in Graph API v2.0. In v2.0 of the API is there is no way to get the FB username of a user.you can use app scope id though as username.

Facebook got rid of the username because the username is one way of sending emails via Facebook. For example, given the url http://www.facebook.com/sebastian.trug the corresponding Facebook email would be sebastian.trug@facebook.com which, if emailed, would be received to messages directly (if the message setting is set to public), otherwise to the other inbox.

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

here is the code for 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)

                }
            })
Girish P
  • 65
  • 1
  • 10
0
[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);
                      }];
Cayke Prudente
  • 220
  • 3
  • 5
0

use this code:

    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];
                         }
                     }];
                }
            }];
Vaibhav Saran
  • 12,848
  • 3
  • 65
  • 75
0

facebook ios sdk get user name and email swift 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")
            }
        })
Raj Joshi
  • 2,669
  • 2
  • 30
  • 37
0

Xcode 8.2.1 and Objective-C

Getting login information any of the place after killing the app

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


                  }];
Saumil Shah
  • 2,299
  • 1
  • 22
  • 27
-2
  1. First you have to get access permission for your App through GraphAPI.

Create a NSMutableDictionary with objectandKey. Your object will be the value which you are reciveing for example your name and your emailId.

Code snippet:

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

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

[params setObject:emailStr forKey:@"email"];
Beryllium
  • 12,808
  • 10
  • 56
  • 86