通过 Facebook Graph API 快速获取个人资料图片返回“不支持的 URL”

Posted

技术标签:

【中文标题】通过 Facebook Graph API 快速获取个人资料图片返回“不支持的 URL”【英文标题】:Getting profile picture with swift through Facebook Graph API return "unsupported URL" 【发布时间】:2015-02-05 00:07:31 【问题描述】:

我正在为 ios 开发一个应用程序,用户应该使用 facebook 登录。所以我试图获取用户的个人资料图片,但以下代码返回"unsupported URL"

FBRequestConnection.startWithGraphpath("\(userID)/picture?type=large&access_token=207613839327374|BgKi3AePtvg1oDO8GTbWqqLE_SM", completionHandler:  (connection, result, error) -> Void in
   if (error? != nil)
      NSLog("error = \(error)")
   else
      println(result)
   
)

更新

以下变化:

FBRequestConnection.startWithGraphPath("\(userID)/picture?type=large", completionHandler:  (connection, result, error) -> Void in
  if (error? != nil)
    NSLog("error = \(error)")
  else
    println(result)
  
)

正在返回:

error = Error Domain=com.facebook.sdk Code=6 "Response is a non-text MIME type; endpoints that return images and other binary data should be fetched using NSURLRequest and NSURLConnection" UserInfo=0x786d4790

【问题讨论】:

【参考方案1】:

你可以这样做:

    // accessToken is your Facebook id
    func returnUserProfileImage(accessToken: NSString)
    
        var userID = accessToken as NSString
        var facebookProfileUrl = NSURL(string: "http://graph.facebook.com/\(userID)/picture?type=large")

        if let data = NSData(contentsOfURL: facebookProfileUrl!) 
            imageProfile.image = UIImage(data: data)
        

    

这是我获得 Facebook id 的方式:

func returnUserData()

    let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
    graphRequest.startWithCompletionHandler( (connection, result, error) -> Void in

        if ((error) != nil)
        
            // Process error
            println("Error: \(error)")
        
        else
        
            println("fetched user: \(result)")

            if let id: NSString = result.valueForKey("id") as? NSString 
                println("ID is: \(id)")
                self.returnUserProfileImage(id)
             else 
                println("ID es null")
            


        
    )

我使用的是 Xcode 6.4Swift 1.2

【讨论】:

这行得通,我认为应该是正确的答案,因为 Parse 没有 PFFacebookUtils.session() 了。 现在使用 swift 3 并尝试了这个,我得到“在展开可选值时意外发现 nil”【参考方案2】:

可以使用以下代码获取它:

    // Get user profile pic
    var fbSession = PFFacebookUtils.session()
    var accessToken = fbSession.accessTokenData.accessToken
    let url = NSURL(string: "https://graph.facebook.com/me/picture?type=large&return_ssl_resources=1&access_token="+accessToken)
    let urlRequest = NSURLRequest(URL: url!)

    NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue.mainQueue())  (response:NSURLResponse!, data:NSData!, error:NSError!) -> Void in

        // Display the image
        let image = UIImage(data: data)
        self.imgProfile.image = image  

    

【讨论】:

PFFacebookUtils 没有与新 ParseSDK 的成员“会话”。【参考方案3】:

您可以使用以下网址简单地获取个人资料图片: https://graph.facebook.com/userID/picture?type=large

其中 userID 是您用户的 Facebook ID。

【讨论】:

srry,它返回 this >> error = Error Domain=com.facebook.sdk Code=6 "响应是非文本 MIME 类型;返回图像和其他二进制数据的端点应该使用NSURLRequest 和 NSURLConnection" 所以你正在尝试打印应该是“NSData”类型的结果? nop,我尝试评论打印行并且错误仍然存​​在 /userID/picture 返回二进制数据(图片本身,而不是图形 API 数据),因此您应该直接使用 NSURLRequest 和 NSURLConnection,而不是创建 FBRequestConnection。 @adolfosrs 如果你想显示图片,使用我的代码,并从你收到的 NSData 创建一个 UIImage。我不明白你为什么要使用 Graph API?除了获取图像本身之外,它还能为您带来什么附加价值?【参考方案4】:

使用 PFFacebookUtils 你可以获得这样的头像:

let pictureRequest = FBSDKGraphRequest(graphPath: "me/picture?type=normal&redirect=false", parameters: nil)
pictureRequest.startWithCompletionHandler(
                            (connection, result, error: NSError!) -> Void in

   if error == nil && result != nil 

     let imageData = result.objectForKey("data") as! NSDictionary
     let dataURL = data.objectForKey("url") as! String
     let pictureURL = NSURL(string: dataURL)
     let imageData = NSData(contentsOfURL: pictureURL!)
     let image = UIImage(data: imageData!)

   
)

【讨论】:

【参考方案5】:

这行代码可以很好地获取个人资料图片。

@IBOutlet var profilePic: UIImageView!
func loginViewFetchedUserInfo(loginView: FBLoginView!, user:      FBGraphUser!) 

    println("User:\(user)")
    println("User ID:\(user.objectID)")
    println("User Name:\(user.name)")
    var userEmail = user.objectForKey("email") as String
    println("User Email:\(userEmail)")
    // Get user profile pic
    let url = NSURL(string: "https://graph.facebook.com/\(user.objectID)/picture?type=large")
    let urlRequest = NSURLRequest(URL: url!)

    NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue.mainQueue())  (response:NSURLResponse!, data:NSData!, error:NSError!) -> Void in

        // Display the image
        let image = UIImage(data: data)
        self.profilePic.image = image

    

【讨论】:

【参考方案6】:

我的例子。请不要关注用户

import Foundation
import FBSDKCoreKit
import FBSDKLoginKit
import SVProgressHUD
import SDWebImage

class FacebookManager 

    // MARK: - functions
    static func getFacebookProfileData(comletion: ((user: User?, error: NSError?) -> ())?) 
        SVProgressHUD.showWithStatus(StringModel.getting)
        let loginManager = FBSDKLoginManager()
        loginManager.loginBehavior = .SystemAccount
        loginManager.logInWithReadPermissions(nil, fromViewController: nil)  (tokenResult, error) in
            if error == nil 
                guard let token = tokenResult?.token?.tokenString else 
                    SVProgressHUD.dismiss()
                    return
                
                getFacebookProfile(token, completion:  (error, user) in
                    if error == nil 
                        comletion?(user: user, error: error)
                        SVProgressHUD.dismiss()
                     else 
                        SVProgressHUD.dismiss()
                        print(error?.localizedDescription)
                    
                )
             else 
                SVProgressHUD.dismiss()
                print(error.localizedDescription)
            
        
    

    private static func getFacebookProfile(token: String, completion: ((error: NSError?, user: User?) -> ())?) 
        FBSDKGraphRequest(graphPath: "me", parameters: ["fields" : "email, name"], HTTPMethod: "GET").startWithCompletionHandler  (requestConnection, result, error) in
            if error == nil 
                guard let resultDictionary = result as? [String : AnyObject] else  return 
                guard let email = resultDictionary["email"] as? String else  return 
                guard let id = resultDictionary["id"] as? String else  return 
                guard let name = resultDictionary["name"] as? String else  return 
                getFacebookProfileImage(id, completion:  (image, error) in
                    if error == nil 
                        let user = User(facebookName: name, facebookID: id, facebookEmail: email, facebookProfileImage: image)
                        completion?(error: nil, user: user)
                    
                )
             else 
                print(error.localizedDescription)
                completion?(error: nil, user: nil)
            
        
    

    private static func getFacebookProfileImage(userID: String, completion: ((image: UIImage?, error: NSError?) -> ())) 
        guard let facebookProfileImageURL = NSURL(string: "https://graph.facebook.com/\(userID)/picture?type=large") else  return 
        print(facebookProfileImageURL)
        let sdImageManager = SDWebImageManager.sharedManager()
        sdImageManager.downloadImageWithURL(facebookProfileImageURL, options: .AvoidAutoSetImage, progress: nil)  (image, error, cachedType, bool, url) in
            if error == nil 
                completion(image: image, error: nil)
             else 
                completion(image: nil, error: error)
                print(error.localizedDescription)
            
        
    

【讨论】:

以上是关于通过 Facebook Graph API 快速获取个人资料图片返回“不支持的 URL”的主要内容,如果未能解决你的问题,请参考以下文章

Facebook Graph API:有应用访问令牌,需要用户访问令牌而无需交互

Facebook Graph API:发布包含多个视频和照片的帖子

通过 Facebook Graph API 上传视频缩略图的问题

有啥方法可以通过 API 创建 facebook 事件,因为 graph api 不再可用

Facebook 分享图标对于通过 Graph API 发布的帖子不可见

无法通过 Graph API 将提要发布到 Facebook 页面