48

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.

1

10 Answers 10

75

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)")
    }
}
8
  • 4
    I was ripping my hair out in the past 3 hours to get the email. They really need to update their docs with these breaking changes. Thank god I found this.
    – Isuru
    Commented Jul 10, 2015 at 20:28
  • @RageCompex, this is a saver for me as well. Thanks a lot. Is that possible to get phone number as well please? Commented Oct 6, 2015 at 20:17
  • see updated answer @Tristan.Liu, phone number is not on the list, but is probably found somewhere else after you have the id. I think you also need to ask that permission.
    – CularBytes
    Commented Oct 7, 2015 at 13:36
  • 1
    I can not get the email. I even added some other fields and I can get those right eg. first_name, last_name, gender they all work well but email is nowhere to be found!! why? Commented Mar 24, 2016 at 5:36
  • 3
    @MasonBallowe Access it as a NSDictionary, eg. let r = result as! NSDictionary, grab values using eg. r["first_name"] Commented May 29, 2016 at 0:13
29
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)
      }
})
1
  • Could not cast value of type '__NSCFDictionary' (0x195fd38a8) to 'NSData' (0x195fd2750). Commented Nov 8, 2016 at 9:47
18

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]])
0
10

Swift 5

Will retrieve the user email, first name, last name & their id by using the GraphRequest class:

// Facebook graph request to retrieve the user email & name
let token = AccessToken.current?.tokenString
let params = ["fields": "first_name, last_name, email"]
let graphRequest = GraphRequest(graphPath: "me", parameters: params, tokenString: token, version: nil, httpMethod: .get)
graphRequest.start { (connection, result, error) in

    if let err = error {
        print("Facebook graph request error: \(err)")
    } else {
        print("Facebook graph request successful!")

        guard let json = result as? NSDictionary else { return }
        if let email = json["email"] as? String {
            print("\(email)")
        }
        if let firstName = json["first_name"] as? String {
            print("\(firstName)")
        }
        if let lastName = json["last_name"] as? String {
            print("\(lastName)")
        }
        if let id = json["id"] as? String {
            print("\(id)")
        }
    }
}
7

Call the below function after you logged in via Facebook.

   func getUserDetails(){

    if(FBSDKAccessToken.current() != nil){

        FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id,name , first_name, last_name , email"]).start(completionHandler: { (connection, result, error) in

            guard let Info = result as? [String: Any] else { return }

             if let userName = Info["name"] as? String
                {
                   print(userName)
                }

        })
    }
}
5

facebook ios sdk get user name and email swift 3

FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, email"]).start(completionHandler: { (connection, result, error) -> Void in
        if (error == nil) {
            let fbDetails = result as! NSDictionary
            print(fbDetails)
        } else {
            print(error?.localizedDescription ?? "Not found")
        }
    })
0
4

you can use this code to get email ,name and profile picture of user

   @IBAction func fbsignup(_ sender: Any) {
    let fbloginManger: FBSDKLoginManager = FBSDKLoginManager()
    fbloginManger.logIn(withReadPermissions: ["email"], from:self) {(result, error) -> Void in
        if(error == nil){
            let fbLoginResult: FBSDKLoginManagerLoginResult  = result!

            if( result?.isCancelled)!{
                return }


            if(fbLoginResult .grantedPermissions.contains("email")){
                self.getFbId()
            }
        }  }

}
func getFbId(){
if(FBSDKAccessToken.current() != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id,name , first_name, last_name , email,picture.type(large)"]).start(completionHandler: { (connection, result, error) in
    guard let Info = result as? [String: Any] else { return } 

            if let imageURL = ((Info["picture"] as? [String: Any])?["data"] as? [String: Any])?["url"] as? String {
        //Download image from imageURL
    }
if(error == nil){
print("result")
}
})
}
}
4

The framework seem to be updated and the way that worked for me is this:

import FacebookCore

let graphRequest: GraphRequest = GraphRequest(graphPath: "me", parameters: ["fields":"first_name,email, picture.type(large)"], accessToken: accessToken, httpMethod: .GET)

graphRequest.start({ (response, result) in
      switch result {
      case .failed(let error):
           print(error)
      case .success(let result):
           if let data = result as? [String : AnyObject] {
              print(data)
           }     
      }
})
2

In Swift 4.2 and Xcode 10.1

@IBAction func onClickFBSign(_ sender: UIButton) {

    if let accessToken = AccessToken.current {
        // User is logged in, use 'accessToken' here.
        print(accessToken.userId!)
        print(accessToken.appId)
        print(accessToken.grantedPermissions!)
        print(accessToken.expirationDate)

        let request = GraphRequest(graphPath: "me", parameters: ["fields":"id,email,name,first_name,last_name,picture.type(large)"], 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)
            }
        }

        let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "SVC") as! SecondViewController
        self.present(storyboard, animated: true, completion: nil)
    } else {

        let loginManager=LoginManager()

        loginManager.logIn(readPermissions: [ReadPermission.publicProfile, .email, .userFriends, .userBirthday], viewController : self) { loginResult in
            switch loginResult {
            case .failed(let error):
                print(error)
            case .cancelled:
                print("User cancelled login")
            case .success(let grantedPermissions, let declinedPermissions, let accessToken):
                print("Logged in : \(grantedPermissions), \n \(declinedPermissions), \n \(accessToken.appId), \n \(accessToken.authenticationToken), \n \(accessToken.expirationDate), \n \(accessToken.userId!), \n \(accessToken.refreshDate), \n \(accessToken.grantedPermissions!)")

                let request = GraphRequest(graphPath: "me", parameters: ["fields": "id, email, name, first_name, last_name, picture.type(large)"], 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)
                    }
                }

                let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "SVC") as! SecondViewController
                self.navigationController?.pushViewController(storyboard, animated: true)

            }
        }
    }

}

For complete details https://developers.facebook.com/docs/graph-api/reference/user

1

In Swift, you can make a Graph request(as shown by @RageCompex) from the login button's didCompleteWithResult callback.

func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!)
    {
        print(result.token.tokenString) //YOUR FB TOKEN
        let req = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"email,name"], tokenString: result.token.tokenString, version: nil, HTTPMethod: "GET")
        req.startWithCompletionHandler({ (connection, result, error : NSError!) -> Void in
            if(error == nil)
            {
                print("result \(result)")
            }
            else
            {
                print("error \(error)")
            }
        })
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.