简体   繁体   中英

How to fetch facebook's profile picture?

I'm trying to fetch the user's fb profile pic but wasn't able to do so far. I'm trying to do something simple: the user log in with fb account and the app goes to another view where appears his name, email and profile picture. User's name and email are okay, but I can't get the picture!

The app is crashing with my actual code because apparently I'm unwrapping a nil optional value, but I don't know why it's nil.

My code:

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.



    let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"id,email,name,picture.width(480).height(480)"])
    graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in


        if ((error) != nil)
        {
            // Process error
            print("Error: \(error)")
        }
        else
        {
            print("fetched user: \(result)")
            let userName : NSString = result.valueForKey("name") as! NSString
            print("User Name is: \(userName)")
            let userEmail : NSString = result.valueForKey("email") as! NSString
            print("User Email is: \(userEmail)")

            let id = result.valueForKey("id") as! String

            self.nameLabel.text = userName as String
            self.emailLabel.text = userEmail as String

            self.profilePic.image = self.getProfPic(id)
        }

    })


}

func getProfPic(fid: String) -> UIImage? {
    if (fid != "") {
        let imgURLString = "http://graph.facebook.com/" + fid + "/picture?type=large" //type=normal
        let imgURL = NSURL(string: imgURLString)
        let imageData = NSData(contentsOfURL: imgURL!)
        let image = UIImage(data: imageData!)  // CODE CRASHES IN HERE
        return image
    }
    return nil
}

From your comments I understand that it crashes at the image assigning, you should be doing it with the conditional binding methodology of Swift (if let) in order to avoid unwrapping a nil optional value:

if let data = result["picture"]?["data"]
{
  if let url = data["url"] as? String
  {
    profilePictureURL = url
  }
}

Also, as you can see I am not using the valueForKey method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM