12

I'm new to iPhone development. I'm doing an App where the user has 2 login through Facebook, once he submits his credentials and clicks on Sign In button, I have to fetch details like First name, email and gender from Facebook and after fetching the user has to be directed to the Registration page of the app with the details filled and i need this app to be compatible for iPhone 4,4s and 5.

I tried doing this using the Facebook Graph API but couldn't get it, so anyone can help me out.

Thanks in Advance.

Mayur Prajapati
  • 5,454
  • 7
  • 41
  • 70
user2419998
  • 131
  • 1
  • 2
  • 4
  • 3
    Welcome to SO. You need to post what you've tried. We'll attempt to assist you, but only after you've shown that you put at least some effort into it. – Steve P. May 25 '13 at 04:59

7 Answers7

18

You can do this by using following code :

[FBSession openActiveSessionWithReadPermissions:@[@"email",@"user_location",@"user_birthday",@"user_hometown"]
                                   allowLoginUI:YES
                              completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {

                                  switch (state) {
                                      case FBSessionStateOpen:
                                          [[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
                                              if (error) {
                                               NSLog(@"error:%@",error);                                               
                                              }
                                              else
                                              {                                                   
                                                  // retrive user's details at here as shown below
                                                  NSLog(@"FB user first name:%@",user.first_name);
                                                  NSLog(@"FB user last name:%@",user.last_name);
                                                  NSLog(@"FB user birthday:%@",user.birthday);
                                                  NSLog(@"FB user location:%@",user.location);
                                                  NSLog(@"FB user username:%@",user.username);
                                                  NSLog(@"FB user gender:%@",[user objectForKey:@"gender"]);
                                                  NSLog(@"email id:%@",[user objectForKey:@"email"]);
                                                  NSLog(@"location:%@", [NSString stringWithFormat:@"Location: %@\n\n",
                                                                         user.location[@"name"]]);

                                              }
                                          }];
                                          break;

                                      case FBSessionStateClosed:
                                      case FBSessionStateClosedLoginFailed:
                                          [FBSession.activeSession closeAndClearTokenInformation];
                                          break;

                                      default:
                                          break;
                                  }

                              } ];

and don't forgot to import FacebookSDK/FacebookSDK.h in your code.

EDIT : Update for Facebook SDK v4 (23 April,2015)

Now, Faceboook have released new SDK with major changes. In which FBSession class is deprecated. So all users are suggested to migrate to new sdk and APIs.

Below I have mentioned, how we can get user details via Facebook SDK v4 :

if ([FBSDKAccessToken currentAccessToken]) {
[[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:nil]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
  if (!error) {
     NSLog(@”fetched user:%@”, result);
  }
 }];
}

But before fetching user details, we have to integrate new Facebook login in our code as described in Documentation here.

Here is the Changelog for SDK v4. I suggest going through it for being updated.

Uniruddh
  • 4,427
  • 3
  • 52
  • 86
  • how to get user phone number? – Muruganandham K Apr 11 '14 at 09:18
  • it is always goes into FBSessionStateClosedLoginFailed... Why...? – Ashish Ramani Apr 16 '14 at 06:57
  • @RamaniAshish : It may be due to permission issue. In order to complete Facebook integration,we must have a working app in FB developer. When we try to use user account details, he has to provide permission to access his/her details. make sure all this things are happening perfectly. This should work as its working for many others including me:) – Uniruddh Apr 16 '14 at 07:04
  • Use `/me` and fill up `parameters` filed with `{ @"fields": @"id,name,email"}`. – Sauvik Dolui Nov 12 '15 at 10:14
3

Add info.plist file:

enter image description here

  - (IBAction)btn_fb:(id)sender
    {
      if (!FBSession.activeSession.isOpen)
            {
                NSArray *_fbPermissions =    @[@"email",@"publish_actions",@"public_profile",@"user_hometown",@"user_birthday",@"user_about_me",@"user_friends",@"user_photos",];

        [FBSession openActiveSessionWithReadPermissions:_fbPermissions allowLoginUI:YES completionHandler:^(FBSession *session,FBSessionState state, NSError *error)
         {
             if (error)
             {
                 UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                 [alertView show];
             }
             else if(session.isOpen)
             {
                 [self btn_fb:sender];
             }


         }];


        return;
    }


    [FBRequestConnection startWithGraphPath:@"me" parameters:[NSDictionary dictionaryWithObject:@"cover,picture.type(large),id,name,first_name,last_name,gender,birthday,email,location,hometown,bio,photos" forKey:@"fields"] HTTPMethod:@"GET" completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
     {
         {
             if (!error)
             {
                 if ([result isKindOfClass:[NSDictionary class]])
                 {
                     NSLog(@"%@",result);

                 }
             }
         }
     }];
}
Gami Nilesh
  • 581
  • 4
  • 19
1

Use the FBConnect API for fetch user information.its easy to use

Fbconnect API

Hope it Works For you :)

Rushabh
  • 3,208
  • 5
  • 28
  • 51
1

you have to use graph path to get user Information.

-(void)getEmailId
{ 
 [facebook requestWithGraphPath:@"me" andDelegate:self];
}

- (void)openSession
{
 if (internetActive) {
  NSArray *permissions=[NSArray arrayWithObjects:@"read_stream",@"email",nil];

  [FBSession openActiveSessionWithReadPermissions:permissions allowLoginUI:YES completionHandler:
   ^(FBSession *session,
   FBSessionState state, NSError *error) {
   [self sessionStateChanged:session state:state error:error];
  }];
 }else
 {
  UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:@"Internet Not Connected" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
  [alert show];
 }
}

#pragma mark- request delegate methods 

- (void)request:(FBRequest *)request didLoad:(id)result
{
  NSLog(@"request did load successfully....");

//  __block NSDictionary *dictionary=[[NSDictionary alloc] init];

 if ([result isKindOfClass:[NSDictionary class]]) {
  NSDictionary* json = result;

  NSLog(@"email id is %@",[json valueForKey:@"email"]);
  NSLog(@"json is %@",json);

  [[NSUserDefaults standardUserDefaults] setValue:[json valueForKey:@"email"] forKey:@"fbemail"];
  [self.viewController login:YES];
 }
}

- (void)request:(FBRequest *)request didFailWithError:(NSError *)error
{
 UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"" message:@"Server not responding.." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];

 [alertView show];

 [self fblogout];
 [self showLoginView];
 NSLog(@"request did fail with error");
}


- (void)sessionStateChanged:(FBSession *)session
                      state:(FBSessionState) state
                      error:(NSError *)error
{
 switch (state) {
  case FBSessionStateOpen: {
      //state open action
  }

   // Initiate a Facebook instance
   facebook = [[Facebook alloc]
                    initWithAppId:FBSession.activeSession.appID
                    andDelegate:nil];

   // Store the Facebook session information
   facebook.accessToken = FBSession.activeSession.accessToken;
   facebook.expirationDate = FBSession.activeSession.expirationDate;

   if (![[NSUserDefaults standardUserDefaults] valueForKey:@"fbemail"]) {
    [MBProgressHUD showHUDAddedTo:self.viewController.view animated:YES];
    [self getEmailId];
   }

   break;
  case FBSessionStateClosed:
  case FBSessionStateClosedLoginFailed:
   // Once the user has logged in, we want them to
   // be looking at the root view.
   [self.navController popToRootViewControllerAnimated:NO];

   [FBSession.activeSession closeAndClearTokenInformation];
   facebook = nil;

   [self showLoginView];
   break;
  default:
   break;
 }

 [[NSNotificationCenter defaultCenter]
  postNotificationName:FBSessionStateChangedNotification
  object:session];

 if (error) {
  UIAlertView *alertView = [[UIAlertView alloc]
                            initWithTitle:@"Error"
                            message:error.localizedDescription
                            delegate:nil
                            cancelButtonTitle:@"OK"
                            otherButtonTitles:nil];
  [alertView show];
 }
}
Prince Kumar Sharma
  • 12,591
  • 4
  • 59
  • 90
1
FBRequest *request = [FBRequest requestForMe];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
    if (!error) {
        // handle successful response
    } else if ([error.userInfo[FBErrorParsedJSONResponseKey][@"body"][@"error"][@"type"] isEqualToString:@"OAuthException"]) { // Since the request failed, we can check if it was due to an invalid session
        NSLog(@"The facebook session was invalidated");
        [self logoutButtonTouchHandler:nil];
    } else {
        NSLog(@"Some other error: %@", error);
    }
}];
SachinVsSachin
  • 6,401
  • 3
  • 33
  • 39
0

Facebook has currently updated their SDK version to 4.x. To Fetch user's profile information you will need to explicitly call graph API after login success (ask for required permissions).

FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
    initWithGraphPath:@"/me"
           parameters:@{ @"fields": @"id,name,email"}
           HTTPMethod:@"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
    // Insert your code here
}];
Sauvik Dolui
  • 5,520
  • 3
  • 34
  • 44