从 Facebook iOS 7 获取用户名和个人资料图片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20623728/
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-30 22:47:55  来源:igfitidea点击:

Getting username and profile picture from Facebook iOS 7

iosobjective-cfacebookfacebook-graph-api

提问by Le'Kirdok

I have read a lot of tutorials about getting information from Facebook, but I have failed so far. I just want to get username and profile picture from Facebook.

我已经阅读了很多关于从 Facebook 获取信息的教程,但到目前为止我都失败了。我只想从 Facebook 获取用户名和个人资料图片。

- (IBAction)login:(id)sender {

   [FBSession openActiveSessionWithReadPermissions:@[@"email",@"user_location",@"user_birthday",@"user_hometown"]
                                   allowLoginUI:YES
                              completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {

   switch (state) {
      case FBSessionStateOpen:
         [[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
            if (error) {
               NSLog(@"error:%@",error);
            } else {
               // retrive user's details at here as shown below
               NSLog(@"FB user first name:%@",user.first_name);
               NSLog(@"FB user last name:%@",user.last_name);
               NSLog(@"FB user birthday:%@",user.birthday);
               NSLog(@"FB user location:%@",user.location);
               NSLog(@"FB user username:%@",user.username);
               NSLog(@"FB user gender:%@",[user objectForKey:@"gender"]);
               NSLog(@"email id:%@",[user objectForKey:@"email"]);
               NSLog(@"location:%@", [NSString stringWithFormat:@"Location: %@\n\n",
                                                                         user.location[@"name"]]);

             }
        }];
        break;
        case FBSessionStateClosed:
        case FBSessionStateClosedLoginFailed:
           [FBSession.activeSession closeAndClearTokenInformation];
        break;
        default:
        break;
       }

   } ];


 }

I used this code for get information, but I cannot get the any information. Can you help me about it? or Can you prefer a tutorial to read it? I have read tutorials on developer.facebook.com.

我使用此代码获取信息,但无法获取任何信息。你能帮我吗?或者你能更喜欢一个教程来阅读它吗?我已阅读 developer.facebook.com 上的教程。

Thank you for your interest.

感谢您的关注。

回答by Guilherme

This is the simplest way I've found to get the user's profile picture.

这是我找到的获取用户个人资料图片的最简单方法。

[[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *FBuser, NSError *error) {
    if (error) {
      // Handle error
    }

    else {
      NSString *userName = [FBuser name];
      NSString *userImageURL = [NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?type=large", [FBuser objectID]];
    }
  }];

Other query parameters that can be used are:

其他可以使用的查询参数有:

  • type: small, normal, large, square
  • width: < value >
  • height: < value >
    • Use both widthand heightto get a cropped, aspect fill image
  • 类型:小、普通、大、方形
  • 宽度:<值>
  • 高度:<值>
    • 使用宽度高度来获得裁剪的纵横填充图像

回答by Hemanshu Liya

if ([FBSDKAccessToken currentAccessToken]) {
    [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:@{ @"fields" : @"id,name,picture.width(100).height(100)"}]startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
        if (!error) {
            NSString *nameOfLoginUser = [result valueForKey:@"name"];
            NSString *imageStringOfLoginUser = [[[result valueForKey:@"picture"] valueForKey:@"data"] valueForKey:@"url"];
            NSURL *url = [[NSURL alloc] initWithURL: imageStringOfLoginUser];
            [self.imageView setImageWithURL:url placeholderImage: nil];
        }
    }];
}

回答by Victor

Make the following Graph request:

发出以下图形请求:

/me?fields=name,picture.width(720).height(720){url}

/me?fields=name,picture.width(720).height(720){url}

And you get really large and cool profile picture:

你会得到非常大和很酷的个人资料图片:

{
  "id": "459237440909381",
  "name": "Victor Mishin", 
  "picture": {
    "data": {
      "url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpf1/t31.0-1/c628.148.1164.1164/s720x720/882111_142093815957080_669659725_o.jpg"
    }
  }
}

P.S. /me?fields=picture.type(large)doesn't do it for me.

PS/me?fields=picture.type(large)不适合我。

回答by akdsouza

You could also get the username and picture as follows:

您还可以按如下方式获取用户名和图片:

[FBSession openActiveSessionWithReadPermissions:@[@"basic_info"]
                                           allowLoginUI:YES
                                      completionHandler:
         ^(FBSession *session, FBSessionState state, NSError *error) {

             if(!error && state == FBSessionStateOpen) {
                 { [FBRequestConnection startWithGraphPath:@"me" parameters:[NSMutableDictionary dictionaryWithObjectsAndKeys:@"id,name,first_name,last_name,username,email,picture",@"fields",nil] HTTPMethod:@"GET" completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
                             NSDictionary *userData = (NSDictionary *)result;
                             NSLog(@"%@",[userData description]);
                         }];
                 }
             }
         }];

Output:
picture =     {
        data =         {
            "is_silhouette" = 0;
            url = "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-frc1/t5.0-1/xxxxxxxxx.jpg";
        };
    };
    username = xxxxxxxxx;

You could just leave the parameter to picture & username and exclude the others based on you requirement. HTH.

您可以将参数保留为图片和用户名,并根据您的要求排除其他参数。哈。

回答by grandagile

This is the code for Facebook SDK 4 and Swift:

这是 Facebook SDK 4 和 Swift 的代码:

if FBSDKAccessToken.currentAccessToken() != nil {
    FBSDKGraphRequest(graphPath: "me", parameters: nil).startWithCompletionHandler({ (connection, result, error) -> Void in
        println("This logged in user: \(result)")
        if error == nil{
            if let dict = result as? Dictionary<String, AnyObject>{
                println("This is dictionary of user infor getting from facebook:")
                println(dict)
            }
        }
    })
}

UPDATE TO ANSWER QUESTIONS:

更新回答问题:

To download public profile image, you get the facebook ID from the dictionary:

要下载公开的个人资料图片,您可以从字典中获取 facebook ID:

let facebookID:NSString = dict["id"] as AnyObject? as NSString

And then call a request to graph API for profile image using the facebook ID:

然后使用 facebook ID 调用对个人资料图像的图形 API 的请求:

let pictureURL = "https://graph.facebook.com/\(fbUserId)/picture?type=large&return_ssl_resources=1"

Sample code:

示例代码:

    let pictureURL = "https://graph.facebook.com/\(fbUserId)/picture?type=large&return_ssl_resources=1"
    //
    var URLRequest = NSURL(string: pictureURL)
    var URLRequestNeeded = NSURLRequest(URL: URLRequest!)
    println(pictureURL)



    NSURLConnection.sendAsynchronousRequest(URLRequestNeeded, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!, error: NSError!) -> Void in
        if error == nil {
            //data is the data of profile image you need. Just create UIImage from it

        }
        else {
            println("Error: \(error)")
        }
    })

回答by Hashim Akhtar

Actually using "http://graph.facebook.com//picture?type=small" to fetch the profile image of the user or even their friends is slow.

实际上使用“ http://graph.facebook.com//picture?type=small”来获取用户甚至他们朋友的个人资料图片很慢。

A better and faster way of doing it to add a FBProfilePictureView object to your view and in it's profileID property, assign the user's Facebook id.

一种更好更快的方法是将 FBProfilePictureView 对象添加到您的视图中,并在它的 profileID 属性中分配用户的 Facebook id。

For example: FBProfilePictureView *friendsPic;

例如:FBProfilePictureView *friendsPic;

friendsPic.profileID = @"1379925668972042";

FriendsPic.profileID = @"1379925668972042";

回答by Jo?o Nunes

Check out this lib: https://github.com/jonasman/JNSocialDownload

查看这个库:https: //github.com/jonasman/JNSocialDownload

you can even get twitter

你甚至可以得到推特