I am trying to fetch the profile picture of the user. But as Facebook has update its API sdk to v4.0 or later, and also on the FB developers site, they are explaining in Objective C, but I want code in Swift. I am not getting how to use FBSDKProfilePicture
in my code. I need help to get profile picture of user.
I want to store the picture in my second view. Please anyone help me to code. Here is my code.
class ViewController: UIViewController, FBSDKLoginButtonDelegate {
let loginManager = FBSDKLoginManager()
let loginView : FBSDKLoginButton = FBSDKLoginButton()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if (FBSDKAccessToken.currentAccessToken() != nil)
{
println("user already logged in")
loginManager.logOut()
// User is already logged in, do work such as go to next view controller.
}
self.view.addSubview(loginView)
loginView.center = self.view.center
loginView.readPermissions = ["public_profile", "email", "user_friends"]
loginView.delegate = self
FBSDKProfile.enableUpdatesOnAccessTokenChange(true)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "onProfileUpdated:", name:FBSDKProfileDidChangeNotification, object: nil)
}
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)")
let userName : NSString = result.valueForKey("name") as! NSString
println("User Name is: \(userName)")
let userEmail : NSString = result.valueForKey("email") as! NSString
println("User Email is: \(userEmail)")
}
})
}
}
If you are able to log in with Facebook, then you should have the FB ID
of that user. With that in hand, you can use this for get the profile picture:
func getProfPic(fid: String) -> UIImage? {
if (fid != "") {
var imgURLString = "http://graph.facebook.com/" + fid! + "/picture?type=large" //type=normal
var imgURL = NSURL(string: imgURLString)
var imageData = NSData(contentsOfURL: imgURL!)
var image = UIImage(data: imageData!)
return image
}
return nil
}
You can also change the type
parameter to a different size in the URL
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With