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,我会看到许多问题和答案。
我已经fields在android中使用过,所以我想也可以在iOS中尝试它,并且可以使用。
fields
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端点,请查看此链接,您可以在其中看到可以获取的所有字段。
User
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)") } }