在 iOS 中从 Facebook 获取用户的个人信息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29471243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 05:31:05  来源:igfitidea点击:

Getting user's Personal info from Facebook in iOS

iosobjective-cfacebookfacebook-sdk-4.0

提问by Simer Sarao

I am quite new to objective-C and iPhone Development environment.

我对objective-C和iPhone开发环境很陌生。

I am implementing Facebook login in my app to get User's name, Email and profile Picture. I have successfully implemented login Part and have received name and User ID of the person.

我正在我的应用程序中实现 Facebook 登录以获取用户的姓名、电子邮件和个人资料图片。我已经成功实现了登录部分,并收到了该人的姓名和用户 ID。

Now i want to get User's Email and Profile Picture from Facebook.But i am not having any Idea how to get it.I am using Facebook IOS SDK v4.0.

现在我想从 Facebook 获取用户的电子邮件和个人资料图片。但我不知道如何获取它。我正在使用 Facebook IOS SDK v4.0。

How can i fetch User's Profile picture and Email Id from Facebook when i am having User ID?

当我有用户 ID 时,如何从 Facebook 获取用户的个人资料图片和电子邮件 ID?

回答by Dheeraj Singh

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

要获取用户电子邮件 ID,您必须在登录时请求电子邮件许可。

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.

您可以使用 GraphPath 在新 SDK 中获取用户电子邮件 ID。

[[[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.

result 将为您提供所有用户详细信息,而 result[@"email"] 将为您提供登录用户的电子邮件。

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 通过传递用户个人资料 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

参考: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]);
             }
         }];

回答by Mustafa Sait Demirci

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.

抱歉这个乱七八糟的答案,这是我有史以来的第一个答案。您可以使用 FBSDK Graph 请求来获取用户的所有个人资料信息和 FBSDKProfilePictureView 类来轻松获取用户的个人资料图片。此代码用于手动 Facebook 登录 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:

您必须向 viewDidLoad 方法添加刷新代码:

   [FBSDKProfile enableUpdatesOnAccessTokenChange:YES];

回答by shikha kochar

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

}

回答by Dnyaneshwar Shinde

#import <FBSDKCoreKit/FBSDKAccessToken.h>
#import <FBSDKCoreKit/FBSDKGraphRequest.h>

Add YourViewController.h

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


    }

}