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

时间:2015-04-06 12:22:24

标签: ios objective-c facebook facebook-sdk-4.0

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

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

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

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

4 个答案:

答案 0 :(得分:55)

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

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

您可以使用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"]);
         }
         }];
    }

结果将为您提供所有用户详细信息和结果[@" 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]);
             }
         }];

答案 1 :(得分:22)

对不起这个凌乱的回答,这是我的第一个回答。您可以使用FBSDK Graph请求获取用户的所有个人资料信息,并使用FBSDKProfilePictureView类轻松获取用户的个人资料图片。此代码用于手动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];
        }        
    }
}]; 

如果登录成功,请实施此方法以获取用户的公开个人资料;

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

答案 2 :(得分:6)

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

}

答案 3 :(得分:1)

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


    }

}