Search code examples
iosfacebookfacebook-graph-apifacebook-ios-sdk

how can i get user information using facebook sdk 4.1 in ios?


I'm using a pre-built login UIButton of Version 2.3 of facebook integration.

Problem: Getting null result, when fetching user details.

-(void) loginButton:(FBSDKLoginButton *)loginButton didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result error:(NSError *)error
{
    if ([FBSDKAccessToken currentAccessToken]) {

            FBSDKGraphRequest *request =[[FBSDKGraphRequest alloc]initWithGraphPath:@"me" parameters:nil];
            [request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
                                          id result,
                                          NSError *error)
    {
        // Handle the result
        NSLog(@"%@",result);
    }];

    FBSDKProfile *profile = [[FBSDKProfile alloc]init];

    }
}

Solution

  • try this code:

    AppDelegate.m

    - (void)applicationDidBecomeActive:(UIApplication *)application {
        [FBSDKAppEvents activateApp];
    
    
         //Default FB Button
        [[NSNotificationCenter defaultCenter]postNotificationName:@"getFacebookData" object:nil];
    }
    
    - (BOOL)application:(UIApplication *)application
                openURL:(NSURL *)url
      sourceApplication:(NSString *)sourceApplication
             annotation:(id)annotation {
        return [[FBSDKApplicationDelegate sharedInstance] application:application
                                                              openURL:url
                                                    sourceApplication:sourceApplication
                                                           annotation:annotation];
    }
    

    ViewDidLoad of viewController

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getFacebookData) name:@"getFacebookData" object:nil];
    
     FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init];
     loginButton.center = self.view.center;
     [self.view addSubview:loginButton];
    

    Add this method in view controller

    - (void)getFacebookData{
        if ([FBSDKAccessToken currentAccessToken]) {
            [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:@{@"fields": @"first_name, last_name, picture.type(large), email, name, id, gender"}]
             startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
                 if (!error) {
                     NSLog(@"fetched user:%@", result);
                 }
             }];
        }
    }