Benja0906 Benja0906 - 4 months ago 16
Swift Question

Swift. Facebook profile picture returning a question mark?

Okay so when I try to recieve the users profil picture, the picture returns a white box with a question mark in it?

Heres my code:

func getProfilePic(fid: String) -> SKTexture? {
let imgURL = NSURL(string: "http://graph.facebook.com/" + fid + "/picture?type=large")
let imageData = NSData(contentsOfURL: imgURL!)
let imageUI = UIImage(data: imageData!)
let image = SKTexture(image: imageUI!)
return image
}

func getFBUserData() {
if((FBSDKAccessToken.currentAccessToken()) != nil) {
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, email, picture"]).startWithCompletionHandler({ (connection, result, error) -> Void in
if (error == nil){
print(result)
if let userData = result as? NSDictionary {
personalUserID = userData["id"] as! String
}
} else {
print("error")
}
})
}
picture.texture = getProfilePic("\(personalUserID)")


How do I get it to show the right picture?

Answer

I'm guessing your profile picture is not available for the public. Now you're not providing an access token with the request, so the request is handled as unauthorised - so you see only what the public eye sees.

To fix it:

func getProfilePic(fid: String) -> SKTexture? {
    let imgURL = NSURL(string: "http://graph.facebook.com/" + fid + "/picture?type=large&access_token=" + FBSDKAccessToken.currentAccessToken().tokenString)
    let imageData = NSData(contentsOfURL: imgURL!)
    let imageUI = UIImage(data: imageData!)
    let image = SKTexture(image: imageUI!)
    return image
}

Also, you'd want to use https and the current API version v2.5 to make the requests, otherwise your code might break in any second when Facebook makes changes. So, with that in mind:

func getProfilePic(fid: String) -> SKTexture? {
    let imgURL = NSURL(string: "https://graph.facebook.com/v2.5/" + fid + "/picture?type=large&access_token=" + FBSDKAccessToken.currentAccessToken().tokenString)
    let imageData = NSData(contentsOfURL: imgURL!)
    let imageUI = UIImage(data: imageData!)
    let image = SKTexture(image: imageUI!)
    return image
}

That should do the trick.

Comments