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.
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@example.com";
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)
}
})
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)
}
})
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": stackoverflow@gmail.com])
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")
}
})
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)
}
})
}
}
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")
}
})
}
}
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)
}
}
})
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)")
}
})
}
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
来源:https://stackoverflow.com/questions/31314124/get-email-and-name-facebook-sdk-v4-4-0-swift