Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get email and name Facebook SDK v4.4.0 Swift

TL;TR: How do I get the email and name of a user that is logged in on my app using the facebook SDK 4.4

So far I have managed to get login working, now I can get the current access token from anywhere in the app.

How I have my login view controller and facebook login button configured:

class LoginViewController: UIViewController, FBSDKLoginButtonDelegate {

    @IBOutlet weak var loginButton: FBSDKLoginButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        if(FBSDKAccessToken.currentAccessToken() == nil)
        {
            print("not logged in")
        }
        else{
            print("logged in already")
        }

        loginButton.readPermissions = ["public_profile","email"]
        loginButton.delegate = self

    }

    //MARK -FB login
    func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
        //logged in
        if(error == nil)
        {
            print("login complete")
            print(result.grantedPermissions)
        }
        else{
            print(error.localizedDescription)
        }

    }

    func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {
        //logout
        print("logout")
    }

Now on my main view I can get the access token like so:

   let accessToken = FBSDKAccessToken.currentAccessToken()
    if(accessToken != nil) //should be != nil
    {
        print(accessToken.tokenString)
    }

How do I get the name and email from the user that is logged in, I see many question and answers using eather an older SDK or using Objective-C.

like image 804
CularBytes Avatar asked Jul 09 '15 09:07

CularBytes


3 Answers

I've used fields in android, so I figured to try it in iOS as well, and it works.

let req = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"email,name"], tokenString: accessToken.tokenString, version: nil, HTTPMethod: "GET")
   req.startWithCompletionHandler({ (connection, result, error : NSError!) -> Void in
       if(error == nil) {
            print("result \(result)")
       } else {
            print("error \(error)")
       }
   }
)

result will print:

result {
   email = "[email protected]";
   id = 123456789;
   name = "Your Name";
}

Found that these fields are equal to the User endpoint, see this link where you can see all the fields that you can get.

Update for Swift 4 and above

let r = FBSDKGraphRequest(graphPath: "me",
                          parameters: ["fields": "email,name"],
                          tokenString: FBSDKAccessToken.current()?.tokenString,
                          version: nil,
                          httpMethod: "GET")

r?.start(completionHandler: { test, result, error in
    if error == nil {
        print(result)
    }
})

Update for Swift 5 with FBSDKLoginKit 6.5.0

guard let accessToken = FBSDKLoginKit.AccessToken.current else { return }
let graphRequest = FBSDKLoginKit.GraphRequest(graphPath: "me",
                                              parameters: ["fields": "email, name"],
                                              tokenString: accessToken.tokenString,
                                              version: nil,
                                              httpMethod: .get)
graphRequest.start { (connection, result, error) -> Void in
    if error == nil {
        print("result \(result)")
    }
    else {
        print("error \(error)")
    }
}
like image 85
CularBytes Avatar answered Oct 09 '22 07:10

CularBytes


let request = GraphRequest.init(graphPath: "me", parameters: ["fields":"first_name,last_name,email, picture.type(large)"], accessToken: AccessToken.current, httpMethod: .GET, apiVersion: FacebookCore.GraphAPIVersion.defaultVersion)

request.start({ (response, requestResult) in
      switch requestResult{
          case .success(let response):
             print(response.dictionaryValue)
          case .failed(let error):
             print(error.localizedDescription)
      }
})
like image 29
Chanchal Raj Avatar answered Oct 09 '22 07:10

Chanchal Raj


For Swift 3 & Facebook SDK 4.16.0:

func getFBUserInfo() {
    let request = GraphRequest(graphPath: "me", parameters: ["fields":"email,name"], accessToken: AccessToken.current, httpMethod: .GET, apiVersion: FacebookCore.GraphAPIVersion.defaultVersion)
    request.start { (response, result) in
        switch result {
        case .success(let value):
            print(value.dictionaryValue)
        case .failed(let error):
            print(error)
        }
    }
}

and will print:

Optional(["id": 1xxxxxxxxxxxxx, "name": Me, "email": [email protected]])
like image 18
JT501 Avatar answered Oct 09 '22 07:10

JT501