patrickhuang94
patrickhuang94

Reputation: 2115

Retrieve Facebook user ID in Swift

I have a helper function that is grabbing the picture from 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 proceed to call getProfilePicture() with the user's Facebook ID, and store the output into a UIImageView. My question is, how can I find a Facebook user's ID? Do I request a connection through Facebook? It would be helpful if some code is provided here.

Thank you for your help.

Upvotes: 6

Views: 5748

Answers (2)

Pat Myron
Pat Myron

Reputation: 4638

If they are already successfully logged into your app:

FBSDKAccessToken.current().userID

Upvotes: 9

dianakarenms
dianakarenms

Reputation: 2695

What worked for me:

  1. Use FBSDKLoginButtonDelegate
  2. Implement func loginButtonWillLogin
  3. Add notification to onProfileUpdated
  4. In onProfileUpdated func proceed to get your Profile info
  5. After onProfileUpdated is called, 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!)")
}
}

Upvotes: 1

Related Questions