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

时间:2015-01-25 00:41:59

标签: ios swift facebook-graph-api facebook-ios-sdk

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

FBSession.openActiveSessionWithReadPermissions(["public_profile"], allowLoginUI: true, completionHandler: {
...
...

所以我要求用户提供信息:

FBRequestConnection.startForMeWithCompletionHandler { (connection, user, error) -> Void in
...
...

为什么用户对象不包含个人资料图片?如何获取用户个人资料图片?它不属于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;
}

P.S:xxx for privacy

10 个答案:

答案 0 :(得分:57)

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

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

这个特殊的网址应该返回" large"用户的个人资料图片的版本,但还有几个照片选项in the docs

答案 1 :(得分:45)

如果您想在与其他用户信息相同的请求中获取图片,则可以在一个图形请求中完成所有操作。它有点乱,但是它再次提出要求。

更多 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
    }
})

Swift 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
    }
})

答案 2 :(得分: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)")
        }
    })

<强>目标-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]);
     }}];

答案 3 :(得分:7)

如果你想获得更大的图片,只需要替换&#34; type = large&#34; to width = XX&amp; 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]); } 
}];

答案 4 :(得分:7)

快速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
            }
        }
    })
}

答案 5 :(得分:4)

@Brandon Gao解决方案给了我一个200X200缩略图...... 为了获得更大的尺寸,我使用FBSDKProfile来获取大小的路径,这也是更模块化的而不是硬编码的(尽管我必须输入 graph.facebook.com 部分...)

let size = CGSize(width: 1080, height: 1080)
let path = FBSDKProfile.currentProfile().imagePathForPictureMode(.Normal, size: size)
let url = "https://graph.facebook.com/\(path)"
Alamofire.request(.GET, url, parameters: nil, encoding: ParameterEncoding.URL).response { 
    (request, response, data, error) -> Void in
    if  let imageData = data as? NSData,
        let image = UIImage(data: imageData) {
            self.buttonImage.setImage(image, forState: .Normal)
    }
}

不知何故,我没有得到1080X1080图像,FB给了我一个1117X1117 ......:\

答案 6 :(得分:4)

对于swift,这是获取照片的网址和特定尺寸的简单方法:

    let params: [NSObject : AnyObject] = ["redirect": false, "height": 800, "width": 800, "type": "large"]
    let pictureRequest = FBSDKGraphRequest(graphPath: "me/picture", parameters: params, HTTPMethod: "GET")
    pictureRequest.startWithCompletionHandler({
        (connection, result, error: NSError!) -> Void in
        if error == nil {
            print("\(result)")


           let dictionary = result as? NSDictionary
           let data = dictionary?.objectForKey("data")
           let urlPic = (data?.objectForKey("url"))! as! String
           print(urlPic)



        } else {
            print("\(error)")
        }
    })

}

答案 7 :(得分:0)

您可以使用此代码For Swift 3.0来获取用户信息

  func getFbId(){
if(FBSDKAccessToken.current() != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id,name , first_name, last_name , email,picture.type(large)"]).start(completionHandler: { (connection, result, error) in
    guard let Info = result as? [String: Any] else { return } 


    if let imageURL = ((Info["picture"] as? [String: Any])?["data"] as? [String: Any])?["url"] as? String {
        //Download image from imageURL
    }
if(error == nil){
print("result")
}
})
}
}

答案 8 :(得分:0)

谢谢@Lyndsey Scott。 对于Kingfisher,请将启用请求http添加到.plist文件中。

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSExceptionDomains</key>
    <dict>
        <key>http://graph.facebook.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>

然后将用户的图片资料设置为ImageView。

let facebookId = "xxxxxxx"
let facebookProfile: String = "http://graph.facebook.com/\(facebookId)/picture?type=large"
let url: URL = URL(string: facebookProfile)!
myImageView.kf.setImage(with: url)

答案 9 :(得分:0)

对于Swift 5

首先添加所需的字段

let params = ["fields": "first_name, last_name, email, picture"]

创建图形请求

let graphRequest = GraphRequest(graphPath: "me", parameters: params, tokenString: token.tokenString, version: nil, httpMethod: .get)
graphRequest.start { (connection, result, error) in }

您将在json中获得结果

{
  "first_name": "",
  "last_name": "",
  "picture": {
    "data": {
      "height": 50,
      "is_silhouette": false,
      "url": "",
      "width": 50
    }
  },
  "id": ""
}

根据json响应,捕获结果

if let error = error {
            print("Facebook graph request error: \(error)")
        } else {
            print("Facebook graph request successful!")
            guard let json = result as? NSDictionary else { return }
            if let id = json["id"] as? String {
                print("\(id)")
            }
            if let email = json["email"] as? String {
                print("\(email)")
            }
            if let firstName = json["first_name"] as? String {
                print("\(firstName)")
            }
            if let lastName = json["last_name"] as? String {
                print("\(lastName)")
            }
            if let profilePicObj = json["picture"] as? [String:Any] {
                if let profilePicData = profilePicObj["data"] as? [String:Any] {
                    print("\(profilePicData)")
                    if let profilePic = profilePicData["url"] as? String {
                        print("\(profilePic)")
                    }
                }
            }
        }
    }

您还可以通过在参数中发送所需的宽度来获取自定义宽度轮廓图片

let params = ["fields": "first_name, last_name, email, picture.width(480)"]

这就是整个代码的样子

if let token = AccessToken.current {
            let params = ["fields": "first_name, last_name, email, picture.width(480)"]
            let graphRequest = GraphRequest(graphPath: "me", parameters: params,
                                            tokenString: token.tokenString, version: nil, httpMethod: .get)
            graphRequest.start { (connection, result, error) in
                if let error = error {
                    print("Facebook graph request error: \(error)")
                } else {
                    print("Facebook graph request successful!")
                    guard let json = result as? NSDictionary else { return }
                    if let id = json["id"] as? String {
                        print("\(id)")
                    }
                    if let email = json["email"] as? String {
                        print("\(email)")
                    }
                    if let firstName = json["first_name"] as? String {
                        print("\(firstName)")
                    }
                    if let lastName = json["last_name"] as? String {
                        print("\(lastName)")
                    }
                    if let profilePicObj = json["picture"] as? [String:Any] {
                        if let profilePicData = profilePicObj["data"] as? [String:Any] {
                            print("\(profilePicData)")
                            if let profilePic = profilePicData["url"] as? String {
                                print("\(profilePic)")
                            }
                        }
                    }
                }
            }
        }

签出Graph API Explorer以获得更多字段。