Получить адрес электронной почты и имя Facebook SDK v4.4.0 Swift
TL; TR: Как получить адрес электронной почты и имя пользователя, зарегистрированного в моем приложении, с помощью фейсбука 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.
Ответы
Ответ 1
Я использовал fields
в Android, поэтому я решил попробовать это в 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 protected]";
id = 123456789;
name = "Your Name";
}
Обнаружено, что эти поля равны конечной точке 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)
}
})
Ответ 2
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)
}
})
Ответ 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": [email protected]])
Ответ 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
Вызовите функцию ниже после того, как вы вошли в систему через 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
Вы можете использовать этот код для получения электронной почты, имени и профиля пользователя
@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
Кажется, что фреймворк обновлен, и у меня так получилось:
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)
}
}
})
Ответ 8
В Swift вы можете сделать запрос Графа (как показано на рисунке @RageCompex) с помощью кнопки входа didCompleteWithResult
.
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
В 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