How to get user info from Facebook SDK in iOS?
Asked Answered
S

5

9

How to get user name when user session is open.I tried the session login sample from Facebook sdk samples. if any one knows the solution please help me out. Thanks in advance.

 - (IBAction)buttonClickHandler:(id)sender {
        // get the app delegate so that we can access the session property
        SLAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];

        // this button's job is to flip-flop the session from open to closed
        if (appDelegate.session.isOpen) {
            // if a user logs out explicitly, we delete any cached token information, and next
            // time they run the applicaiton they will be presented with log in UX again; most
            // users will simply close the app or switch away, without logging out; this will
            // cause the implicit cached-token login to occur on next launch of the application
   //hear i need to fetch user name ?


            [appDelegate.session closeAndClearTokenInformation];

        } else {
            if (appDelegate.session.state != FBSessionStateCreated) {
                // Create a new, logged out session.
                appDelegate.session = [[FBSession alloc] init];
            }

            // if the session isn't open, let's open it now and present the login UX to the user
            [appDelegate.session openWithCompletionHandler:^(FBSession *session,
                                                             FBSessionState status,
                                                             NSError *error) {
                // and here we make sure to update our UX according to the new session state
                [self updateView];
            }];
        }
    }
Spirituel answered 1/3, 2014 at 8:22 Comment(1)
developers.facebook.com/docs/ios/graphDolores
R
32

After login authentication, you can get details from active FBSession like below

if (FBSession.activeSession.isOpen) {

    [[FBRequest requestForMe] startWithCompletionHandler:
     ^(FBRequestConnection *connection,
       NSDictionary<FBGraphUser> *user,
       NSError *error) {
         if (!error) {
             NSString *firstName = user.first_name;
             NSString *lastName = user.last_name;
             NSString *facebookId = user.id;
             NSString *email = [user objectForKey:@"email"];
             NSString *imageUrl = [[NSString alloc] initWithFormat: @"http://graph.facebook.com/%@/picture?type=large", facebookId];
         }
     }];
}

Update: Instead of id use objectID property, after release of version v3.14.1(May 12, 2014), the id property has been deprecated

NSString *facebookId = user.objectID;
Reider answered 1/3, 2014 at 9:28 Comment(10)
@PeerMohamedThabib What you got as error? did you got call back?Reider
What you mean by fbfetchRequest?Reider
The latest Facebook SDK recommends using user.objectID instead of user.id ('id' is deprecated, I guess to avoid conflicts with Objective-c id object)Corkwood
@Corkwood I didn't check with latest sdk. If you know exact version of sdk, please feel free to update my answer.Reider
From version v3.14.1 - May 12, 2014, the id property has been deprecated developers.facebook.com/docs/ios/change-log-3.xCorkwood
@Corkwood Don't try to replace my answer. Instead, Please just update my answer with heading Update.Reider
@Reider Is this a way FBLoginView does things? I'm just uneasy with the idea of making one request to log in user (startup session), and another afterwards to get needed data about user. It should be in one request I think..Pestalozzi
@bluesm should not be. Because FBLoginView create session and set as active session after authentication. So It wouldn't return user info. Anyway please check with recent docs developers.facebook.com/docs/reference/ios/current/class/….Reider
user.objectID = Invalid expression (3.21.1)Sherellsherer
user.objectID is invalid, but code insight says "id is deprecated - use objectID instead"… ridiculousSherellsherer
T
6

Hi you can get the details of Facebook user like:

- (void)sessionStateChanged:(NSNotification*)notification {
    if ([[FBSession activeSession] isOpen]) {
        [FBRequestConnection
         startForMeWithCompletionHandler:^(FBRequestConnection *connection,
                                           id<FBGraphUser> user,
                                           NSError *error) {
             if (! error) {

                //details of user
                NSLog(@"User details =%@",user);
             }
         }];
    }else {
        [[FBSession activeSession] closeAndClearTokenInformation];
    }
}

Thanks

Thermophone answered 1/3, 2014 at 9:2 Comment(0)
Q
1
if (!error && state == FBSessionStateOpen){
    NSLog(@"Session opened");
    // Show the user the logged-in UI
     FBRequest* userupdate = [FBRequest requestWithGraphPath:@"me" parameters: [NSMutableDictionary dictionaryWithObject:@"picture.type(large),id,birthday,email,gender,username,name,first_name" forKey:@"fields"] HTTPMethod:@"GET"];
    [drk showWithMessage:nil];
    [userupdate startWithCompletionHandler: ^(FBRequestConnection *connection,
                                          NSDictionary* result,NSError *error)
   {
    NSLog(@"dict = %@",result);
   }];
    return;
}
Qualifier answered 1/3, 2014 at 9:12 Comment(0)
D
1
        FBSDKGraphRequest(graphPath: "me", parameters: nil).startWithCompletionHandler({ (connection, object, error) in
            guard let user = object as? Dictionary<String, NSObject> else {
                alert("facebook sdk gave me trash object \(object)")
                return
            }
            if let error = error {
                alert(error.localizedDescription)
            }
            else {
                if let userID = user["id"] {
                   // gr8t success

                }

            }
        })
Disannul answered 5/10, 2016 at 12:9 Comment(0)
H
-1
-(void)loginViewFetchedUserInfo:(FBLoginView *)loginView user:(id<FBGraphUser>)user {
  
    
    NSLog(@"user facebook details:%@",user.objectID);
    
   }

You can implement this delegate method.

Heptad answered 16/12, 2014 at 10:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.