【问题标题】:Get email and name Facebook SDK v4.4.0 Swift获取电子邮件并命名 Facebook SDK v4.4.0 Swift
【发布时间】:2015-09-27 15:07:20
【问题描述】:

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。

【问题讨论】:

标签: ios swift xcode cocoa-touch facebook-sdk-4.0


【解决方案1】:

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

【讨论】:

  • 在过去的 3 个小时里,为了收到这封电子邮件,我一直在扯头发。他们确实需要使用这些重大更改来更新他们的文档。感谢上帝,我找到了这个。
  • @RageCompex,这对我来说也很省钱。非常感谢。请问这样可以获取电话号码吗?
  • 查看更新的答案@Tristan.Liu,电话号码不在列表中,但在您获得 id 后可能会在其他地方找到。我认为您还需要获得该许可。
  • 我收不到邮件。我什至添加了一些其他字段,我可以得到正确的,例如。名字,姓氏,性别它们都很好用,但找不到电子邮件!为什么?
  • @MasonBallowe 作为 NSDictionary 访问它,例如。 let r = result as! NSDictionary,使用例如获取值。 r["first_name"]
【解决方案2】:

在 Swift 中,您可以从登录按钮的 didCompleteWithResult 回调中发出 Graph 请求(如 @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)")
            }
        })
}

【讨论】:

    【解决方案3】:

    对于 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": stackoverflow@gmail.com])
    

    【讨论】:

      【解决方案4】:
      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)
            }
      })
      

      【讨论】:

      • 无法将“__NSCFDictionary”(0x195fd38a8)类型的值转换为“NSData”(0x195fd2750)。
      【解决方案5】:

      facebook ios sdk 快速获取用户名和电子邮件 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")
              }
          })
      

      【讨论】:

        【解决方案6】:

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

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

        【讨论】:

          【解决方案7】:

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

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

          【讨论】:

            【解决方案8】:

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

            【讨论】:

              【解决方案9】:

              在 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

              【讨论】:

                【解决方案10】:

                斯威夫特 5

                将使用@987654321 检索用户电子邮件名字及其id @类:

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

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2023-04-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多