Ios 通过Facebook Graph API return获取swift的个人资料图片;不支持的URL“;

Ios 通过Facebook Graph API return获取swift的个人资料图片;不支持的URL“;,ios,facebook,facebook-graph-api,swift,Ios,Facebook,Facebook Graph Api,Swift,我正在为iOS开发一个应用程序,用户应该登录facebook。因此,我试图获取用户配置文件图片,但下面的代码返回了“不支持的URL” 更新 以下更改: FBRequestConnection.startWithGraphPath("\(userID)/picture?type=large", completionHandler: { (connection, result, error) -> Void in if (error? != nil){ NSL

我正在为iOS开发一个应用程序,用户应该登录facebook。因此,我试图获取用户配置文件图片,但下面的代码返回了
“不支持的URL”


更新 以下更改:

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

您只需使用以下url获取配置文件pic:


其中userID是您用户的Facebook ID。

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

    // 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  

    }

这行代码可以很好地用于获取配置文件Pic

@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

    }
}

您可以这样做:

    // 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

使用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!)

   }
})

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

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

SRY,其返回此>>错误=错误域=com.facebook.sdk代码=6“响应是非文本MIME类型;返回图像和其他二进制数据的端点应使用NSURLRequest和NSURLConnection获取”,因此您尝试打印的结果应为“NSData”类型?否,我尝试对打印行进行注释,但错误仍然存在/userID/picture返回二进制数据(图片本身,而不是图形API数据),因此您应该直接使用NSURLRequest和NSURLConnection,而不是创建FBRequestConnection。@adolfosrs如果要显示图片,请使用我的代码,并根据收到的NSR数据创建UIImage。我不明白你为什么要使用图形API?除了获取图像本身,它还会给您带来什么额外的价值?PFFacebookUtils没有新ParseSDK的成员“会话”。这很有效,我认为这应该是正确的答案,因为Parse不再有PFFacebookUtils.session()。现在使用swift 3并尝试了这一点,我得到了“在打开可选值时意外地发现了nil”
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)
            }
        }
    }
}