获取电子邮件并命名 Facebook SDK v4.4.0 Swift

Get email and name Facebook SDK v4.4.0 Swift

TL;TR:如何获取使用 Facebook SDK 4.4 登录我的应用程序的用户的电子邮件和姓名

到目前为止,我已经成功登录,现在我可以从应用程序中的任何位置获取当前访问令牌。

我如何配置我的登录视图控制器和 facebook 登录按钮:

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")
    }

现在在我的主视图上,我可以像这样获取访问令牌:

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

如何从已登录的用户处获取姓名和电子邮件,我看到许多问题和答案使用较旧的 SDK 或使用 Objective-C。

我在 android 中使用过 fields,所以我想在 iOS 中也尝试一下,并且有效。

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 {
   email = "email@example.com";
   id = 123456789;
   name = "Your Name";
}

发现这些字段等于User端点,查看this link那里可以看到所有可以获取的字段。

更新 Swift 4 及更高版本

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)
    }
})

使用 FBSDKLoginKit 6.5.0 Swift 5 的更新

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)")
    }
}

在 Swift 中,您可以从登录按钮的 didCompleteWithResult 回调中发出图表请求(如@RageCompex 所示)。

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)")
            }
        })
}

对于 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)
        }
    }
}

并将打印:

Optional(["id": 1xxxxxxxxxxxxx, "name": Me, "email": Whosebug@gmail.com])
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)
      }
})

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")
        }
    })

框架似乎已更新,对我有用的方式是这样的:

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)
           }     
      }
})

你 可以使用此代码获取用户的电子邮件、姓名和个人资料图片

   @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")
}
})
}
}

通过 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)
                }

        })
    }
}

在 Swift 4.2 和 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)

            }
        }
    }

}

完整的细节https://developers.facebook.com/docs/graph-api/reference/user

Swift 5

将检索用户电子邮件名字姓氏及其id 通过使用 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)")
        }
    }
}