web-dev-qa-db-ja.com

Facebook GraphAPIを介してSwiftでプロフィール写真を取得すると、「サポートされていないURL」が返されます

ユーザーがFacebookでログインする必要があるiOS用のアプリを開発しています。だから私はユーザーのプロフィール写真を取得しようとしていますが、次のコードは"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
11
adolfosrs

このコードを使用して取得できます:

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

    }
10
user1872384

あなたはこの方法でそれを行うことができます:

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

    }

これは私が私のFacebookIDを取得した方法です:

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を使用していました

12
Jorge Casariego

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

   }
})
2
Phil Andrews

次のURLを使用して、プロフィール写真を簡単に取得できます。 https://graph.facebook.com/userID/picture?type=large

ここで、userIDはユーザーのFacebookIDです。

2
Dani A

私の例。ユーザーに注意を払わないでください

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

このコード行は、プロファイル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

    }
}
1