Get email and name Facebook SDK v4.4.0 Swift
Asked Answered
V

10

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.

Villalobos answered 9/7, 2015 at 9:55 Comment(1)
#31384078Graver
V
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)")
    }
}
Villalobos answered 9/7, 2015 at 9:55 Comment(8)
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.Greatgranduncle
@RageCompex, this is a saver for me as well. Thanks a lot. Is that possible to get phone number as well please?Gunsel
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.Villalobos
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?Earp
Because you need to request the email permission when logging in.Villalobos
How do i retrieve individual components of the result? I tried result.name, result.email, but it isn't giving me anything.Isomagnetic
@MasonBallowe Access it as a NSDictionary, eg. let r = result as! NSDictionary, grab values using eg. r["first_name"]Acescent
If you didn't get the email address change version from nil to "v2.3"Impudent
B
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)
      }
})
Bronchitis answered 1/11, 2016 at 8:3 Comment(1)
Could not cast value of type '__NSCFDictionary' (0x195fd38a8) to 'NSData' (0x195fd2750).Khartoum
O
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]])
Occam answered 9/10, 2016 at 9:2 Comment(0)
W
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)")
        }
    }
}
Whinstone answered 17/4, 2020 at 11:2 Comment(0)
S
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)
                }

        })
    }
}
Saucier answered 25/10, 2018 at 1:44 Comment(0)
Q
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")
        }
    })
Quibbling answered 7/3, 2017 at 12:26 Comment(0)
T
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)
           }     
      }
})
Turves answered 28/9, 2017 at 6:33 Comment(0)
H
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")
}
})
}
}
Hayfield answered 12/2, 2018 at 11:57 Comment(0)
G
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

Graver answered 13/2, 2019 at 11:0 Comment(0)
A
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)")
            }
        })
}
Amidase answered 2/5, 2016 at 9:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.