Get Swift Facebook User ID

I have a helper function that captures an image at a specific URL:

func getProfilePicture(fid: String) -> UIImage? { if (fid != "") { var imageURLString = "http://graph.facebook.com/" + fid + "/picture?type=large" var imageURL = NSURL(string: imageURLString) var imageData = NSData(contentsOfURL: imageURL!) var image = UIImage(data: imageData!) return image } return nil } 

I go to the getProfilePicture () call with the Facebook user ID and save the output to UIImageView. My question is: how can I find the Facebook user ID? Request a connection via Facebook? It would be helpful if the code was given here.

Thank you for your help.

+5
source share
2 answers

If they have already successfully logged into your application:

 FBSDKAccessToken.current().userID 
+6
source

What worked for me:

  • Use FBSDKLoginButtonDelegate
  • Implementation of func loginButtonWillLogin
  • Add notification for onProfileUpdated
  • In onProfileUpdated func go to your profile information
  • After calling onProfileUpdated, you can use your FBSDKProfile in any controller

And now, some Swift 3 code ...

 import UIKit import FBSDKLoginKit class ViewController: UIViewController, FBSDKLoginButtonDelegate { override func viewDidLoad() { super.viewDidLoad() // Facebook login integration let logBtn = FBSDKLoginButton() logBtn.center = self.view.center self.view .addSubview(logBtn) logBtn.delegate = self } func loginButtonWillLogin(_ loginButton: FBSDKLoginButton!) -> Bool { print("will Log In") FBSDKProfile.enableUpdates(onAccessTokenChange: true) NotificationCenter.default.addObserver(self, selector: #selector(onProfileUpdated(notification:)), name:NSNotification.Name.FBSDKProfileDidChange, object: nil) return true } func onProfileUpdated(notification: NSNotification) { print("profile updated") print("\(FBSDKProfile.current().userID!)") print("\(FBSDKProfile.current().firstName!)") } } 
+1
source

All Articles