Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 769
patrickhuang94 Avatar asked Jul 02 '15 21:07

patrickhuang94


2 Answers

If they are already successfully logged into your app:

FBSDKAccessToken.current().userID
like image 197
Pat Myron Avatar answered Nov 03 '22 08:11

Pat Myron


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!)")
}
}
like image 31
dianakarenms Avatar answered Nov 03 '22 10:11

dianakarenms