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

时间:2015-07-09 09:55:35

标签: swift facebook-sdk-4.0

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查看了许多问题和答案。

10 个答案:

答案 0 :(得分:57)

我已经在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,您可以在其中查看可以获得的所有字段。

答案 1 :(得分:27)

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

答案 2 :(得分:18)

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

答案 3 :(得分:5)

雨燕5

将通过使用{{来检索用户电子邮件名字姓氏及其 id 1}}类:

GraphRequest

答案 4 :(得分:4)

  

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

答案 5 :(得分:4)

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

        })
    }
}

答案 6 :(得分:3)

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

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

答案 7 :(得分:2)

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

if (yourView.isHidden) {

    NSLog(@"view is hidden");
}
else{

    NSLog(@"view is not hidden");
}

答案 8 :(得分:1)

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

答案 9 :(得分:0)

在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