Getting user's Personal info from Facebook in iOS

别来无恙 提交于 2019-11-28 04:33:25

To get user Email ID you must ask permission for email while logging.

FBSDKLoginButton *loginView = [[FBSDKLoginButton alloc] init];
loginView.readPermissions =  @[@"email"];
loginView.frame = CGRectMake(100, 150, 100, 40);
[self.view addSubview:loginView];

You can get user email Id in New SDK using GraphPath.

[[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:nil]
         startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {

             if (!error) {
                 NSLog(@"fetched user:%@  and Email : %@", result,result[@"email"]);
         }
         }];
    }

result would get you all the user Details and result[@"email"] would get you the email for logged in user.

To get Profile picture you can use

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?type=normal",result[@"id"]]];
NSData  *data = [NSData dataWithContentsOfURL:url];
_imageView.image = [UIImage imageWithData:data]; 

or u can also use FBSDKProfilePictureView to get profile Picture by passing user profile Id:

FBSDKProfilePictureView *profilePictureview = [[FBSDKProfilePictureView alloc]initWithFrame:_imageView.frame];
[profilePictureview setProfileID:result[@"id"]];
[self.view addSubview:profilePictureview];

Refer to :https://developers.facebook.com/docs/facebook-login/ios/v2.3#profile_picture_view

or u can also get both by passing as parameters

[[[FBSDKGraphRequest alloc] initWithGraphPath:@"me"
                                           parameters:@{@"fields": @"picture, email"}]
         startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
             if (!error) {
                 NSString *pictureURL = [NSString stringWithFormat:@"%@",[result objectForKey:@"picture"]];

                 NSLog(@"email is %@", [result objectForKey:@"email"]);

                 NSData  *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:pictureURL]];
                 _imageView.image = [UIImage imageWithData:data];

             }
             else{
                 NSLog(@"%@", [error localizedDescription]);
             }
         }];

Sorry for this messy answer, this is my first answer ever. You can use FBSDK Graph request to fetch user's all profile infos and FBSDKProfilePictureView class to fetch user's Profile Picture easily.This code is for manually Facebook login UI.

Firstly, you must put this code where login process start:

 FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];

[login logInWithReadPermissions:@[@"public_profile", @"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {

    if (error)
    {

     // There is an error here.

    }
    else
    {
        if(result.token)   // This means if There is current access token.
        {    
            // Token created successfully and you are ready to get profile info
            [self getFacebookProfileInfo];
        }        
    }
}]; 

And If login is successfull, implement this method to get user's public profile;

-(void)getFacebookProfileInfos { 

FBSDKGraphRequest *requestMe = [[FBSDKGraphRequest alloc]initWithGraphPath:@"me" parameters:nil];

FBSDKGraphRequestConnection *connection = [[FBSDKGraphRequestConnection alloc] init];

[connection addRequest:requestMe completionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {

      if(result)
      {            
        if ([result objectForKey:@"email"]) {

          NSLog(@"Email: %@",[result objectForKey:@"email"]);

        }
        if ([result objectForKey:@"first_name"]) {

          NSLog(@"First Name : %@",[result objectForKey:@"first_name"]);

        }
        if ([result objectForKey:@"id"]) {

          NSLog(@"User id : %@",[result objectForKey:@"id"]);

        }

      }

 }];

[connection start];

Get current logged in user's profile picture:

FBSDKProfilePictureView *pictureView=[[FBSDKProfilePictureView alloc]init];

[pictureView setProfileID:@"user_id"];

[pictureView setPictureMode:FBSDKProfilePictureModeSquare];

[self.view addSubview:pictureView];

You must add refreshing code to your viewDidLoad method:

   [FBSDKProfile enableUpdatesOnAccessTokenChange:YES];
Hope This could Help You ..

- (IBAction)Loginwithfacebookaction:(id)sender
{


    FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
    [login logOut];

    [login logInWithReadPermissions:@[@"public_profile"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
        if (error)
        {
            NSLog(@"Process error");
        }
        else if (result.isCancelled)
        {
            NSLog(@"Cancelled");
        }
        else
        {
            [self getFacebookProfileInfos];
        }
    }];
 }

- (void)finishedWithAuth: (GTMOAuth2Authentication *)auth
                   error: (NSError *) error {

    NSLog(@"Received error %@ and auth object %@",error, auth);
    if (!error)
    {
        email =signIn.userEmail;
        [[NSUserDefaults standardUserDefaults] setObject:email forKey:@"useremail"];
        NSLog(@"Received error and auth object %@",signIn.userEmail);
        NSLog(@"Received error and auth object %@",signIn.userID);
        if ( auth.userEmail)
        {
            [[[GPPSignIn sharedInstance] plusService] executeQuery:[GTLQueryPlus queryForPeopleGetWithUserId:@"me"] completionHandler:^(GTLServiceTicket *ticket, GTLPlusPerson *person, NSError *error)
             {
                 // this is for fetch profile image
                 NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",person.image.url]];
                 NSLog(@"%@",url);
                 name= person.displayName;
                     [[NSUserDefaults standardUserDefaults] setObject:name forKey:@"userNameLogin"];
                     [[NSUserDefaults standardUserDefaults] synchronize];
                NSLog(@"Name:%@",person.displayName);
                 [self callWebserviceToUploadImage];
             }];

        }
    }
}

-(void)getFacebookProfileInfos {

    FBSDKGraphRequest *requestMe = [[FBSDKGraphRequest alloc]initWithGraphPath:@"/me?fields=first_name, last_name, picture, email" parameters:nil];

    FBSDKGraphRequestConnection *connection = [[FBSDKGraphRequestConnection alloc] init];


    [connection addRequest:requestMe completionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {

        if(result)
        {
            if ([result objectForKey:@"email"]) {
                email = [result objectForKey:@"email"];

                [[NSUserDefaults standardUserDefaults] setObject:email forKey:@"useremail"];

            }
            if ([result objectForKey:@"first_name"]) {

                NSLog(@"First Name : %@",[result objectForKey:@"first_name"]);
                 name = [result objectForKey:@"first_name"];
                [[NSUserDefaults standardUserDefaults] setObject:name forKey:@"userNameLogin"];

            }
            if ([result objectForKey:@"id"])
            {

                NSLog(@"User id : %@",[result objectForKey:@"id"]);

            }
        }
        [self callfbloginwebservice];

    }];
    [connection start];

}
Dnyaneshwar Shinde
#import <FBSDKCoreKit/FBSDKAccessToken.h>
#import <FBSDKCoreKit/FBSDKGraphRequest.h>

Add YourViewController.h

- (IBAction)loginAction:(id)sender {

   // https://developers.facebook.com/docs/graph-api/reference/user
  //  https://developers.facebook.com/docs/ios/graph


    if ([FBSDKAccessToken currentAccessToken]) {
        [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:@{@"fields": @"email,name,first_name,last_name"}]
         startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
             if (!error) {
                 NSLog(@"fetched user:%@", result);
                // Here u can update u r UI like email name TextField
             }
         }];


    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!