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

Getting user's Personal info from Facebook in iOS

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

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

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

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

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

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

您可以使用 GraphPath 在 New 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 将为您提供所有用户详细信息,result[@"email"] 将为您提供登录用户的电子邮件。

要获取个人资料图片,您可以使用

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

或者您也可以使用 FBSDKProfilePictureView 通过传递用户个人资料 ID 来获取个人资料图片:

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

参考:https://developers.facebook.com/docs/facebook-login/ios/v2.3#profile_picture_view

或者你也可以通过传递参数来获得两者

[[[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]);
             }
         }];

抱歉这个乱七八糟的回答,这是我第一次回答。您可以使用 FBSDK Graph 请求获取用户的所有个人资料信息,并使用 FBSDKProfilePictureView class 获取用户的个人资料图片 easily.This 代码用于手动 Facebook 登录 UI。

首先,您必须将这段代码放在登录过程开始的地方:

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

并且如果登录成功,执行此方法以获取用户的 public 个人资料;

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

获取当前登录用户的头像:

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

[pictureView setProfileID:@"user_id"];

[pictureView setPictureMode:FBSDKProfilePictureModeSquare];

[self.view addSubview:pictureView];

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

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

}
#import <FBSDKCoreKit/FBSDKAccessToken.h>
#import <FBSDKCoreKit/FBSDKGraphRequest.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
             }
         }];


    }

}