Facebook iOS SDK和swift:如何获取用户的个人资料图片

Tom*_*Tom 24 facebook-graph-api ios facebook-ios-sdk swift

我已经在Xcode 6中集成了Facebook sdk(使用swift).在登录期间,我请求public_profile权限:

FBSession.openActiveSessionWithReadPermissions(["public_profile"], allowLoginUI: true, completionHandler: {
...
...
Run Code Online (Sandbox Code Playgroud)

所以我请求用户的信息:

FBRequestConnection.startForMeWithCompletionHandler { (connection, user, error) -> Void in
...
...
Run Code Online (Sandbox Code Playgroud)

为什么用户对象不包含个人资料图片?如何获取用户个人资料图片?它不是public_profile的一部分?

我得到以下信息:

2015-01-25 01:25:18.858 Test[767:23804] {
"first_name" = xxx;
gender = xxx;
id = xxxxxxxxx;
"last_name" = xxxxxx;
link = "https://www.facebook.com/app_scoped_user_id/xxxxxxxxx/";
locale = "xxxxx";
name = "xxxxxxx xxxxxxx";
timezone = 1;
"updated_time" = "2013-12-21T18:45:29+0000";
verified = 1;
}
Run Code Online (Sandbox Code Playgroud)

PS:隐私的xxx

Lyn*_*ott 58

个人资料图片实际上是公开的,您只需将用户ID添加到Facebook指定的个人资料图片网址,例如:

var userID = user["id"] as NSString     
var facebookProfileUrl = "http://graph.facebook.com/\(userID)/picture?type=large"
Run Code Online (Sandbox Code Playgroud)

此特定网址应返回用户个人资料图片的"大"版本,但文档中还提供了更多照片选项.

  • 那正是我所想.令人惊讶的是,即使没有"正式"记录,使用`type = large`或其他(我使用`width = 150&height = 150`)似乎工作正常.谢谢! (2认同)
  • 谢谢@LyndseyScott - 对于将来使用此功能的用户,请不要忘记使用"https"代替"http"来消除Apple Security投诉:) (2认同)

Mic*_*son 49

如果您想在与其他用户信息相同的请求中获取图片,则可以在一个图形请求中完成所有操作.它有点乱,但它打败了另一个请求.

一个更Swift 3的方法

let request = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, email, picture.type(large)"])
let _ = request?.start(completionHandler: { (connection, result, error) in
    guard let userInfo = result as? [String: Any] else { return } //handle the error

    //The url is nested 3 layers deep into the result so it's pretty messy
    if let imageURL = ((userInfo["picture"] as? [String: Any])?["data"] as? [String: Any])?["url"] as? String {
        //Download image from imageURL
    }
})
Run Code Online (Sandbox Code Playgroud)

斯威夫特2

let request = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, email, picture.type(large)"])
request.startWithCompletionHandler({ (connection, result, error) in
    let info = result as! NSDictionary
    if let imageURL = info.valueForKey("picture")?.valueForKey("data")?.valueForKey("url") as? String {
        //Download image from imageURL
    }
})
Run Code Online (Sandbox Code Playgroud)


小智 27

使用Facebook SDK 4.0,您可以使用:

迅速:

    let pictureRequest = FBSDKGraphRequest(graphPath: "me/picture?type=large&redirect=false", parameters: nil)
    pictureRequest.startWithCompletionHandler({
        (connection, result, error: NSError!) -> Void in
        if error == nil {
            println("\(result)")
        } else {
            println("\(error)")
        }
    })
Run Code Online (Sandbox Code Playgroud)

Objective-C的:

FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
                                  initWithGraphPath:[NSString stringWithFormat:@"me/picture?type=large&redirect=false"]
                                  parameters:nil
                                  HTTPMethod:@"GET"];
    [request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
                                          id result,
                                          NSError *error) {
    if (!error){
       NSLog(@"result: %@",result);}
    else {
       NSLog(@"result: %@",[error description]);
     }}];
Run Code Online (Sandbox Code Playgroud)


San*_*rma 9

Swift 4方法: -

private func fetchUserData() {
    let graphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"id, email, name, picture.width(480).height(480)"])
    graphRequest?.start(completionHandler: { (connection, result, error) in
        if error != nil {
            print("Error",error!.localizedDescription)
        }
        else{
            print(result!)
            let field = result! as? [String:Any]
            self.userNameLabel.text = field!["name"] as? String
            if let imageURL = ((field!["picture"] as? [String: Any])?["data"] as? [String: Any])?["url"] as? String {
                print(imageURL)
                let url = URL(string: imageURL)
                let data = NSData(contentsOf: url!)
                let image = UIImage(data: data! as Data)
                self.profileImageView.image = image
            }
        }
    })
}
Run Code Online (Sandbox Code Playgroud)


jim*_*jim 7

如果你想获得更大的图片,只需将"type = large"替换为width = XX&height = XX

但你可以得到的最大图片是原始图片

FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] 
                              initWithGraphPath:@"me/picture?width=1080&height=1080&redirect=false" 
                              parameters:nil 
                              HTTPMethod:@"GET"]; 

[request startWithCompletionHandler:^(
                            FBSDKGraphRequestConnection *connection,
                            id result, 
                            NSError *error) { 
if (!error) 
{ 
   NSLog(@"result = %@",result);
   NSDictionary *dictionary = (NSDictionary *)result; 
   NSDictionary *data = [dictionary objectForKey:@"data"]; 
   NSString *photoUrl = (NSString *)[data objectForKey:@"url"]; 
} 
else 
{ 
   NSLog(@"result = %@",[error description]); } 
}];
Run Code Online (Sandbox Code Playgroud)