Facebook SDK in Swift - ios

I am trying to integrate Facebook login and more into my app but am having a lot of difficulty because there is not much documentation in Swift. I am trying to use this code:
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"/me"
parameters:#{ #"fields": #"id,name,friends,birthday,gender,first_name,last_name,friendlists,picture",}
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
// Insert your code here
}];
Any idea what this would be in Swift?

FBSDKGraphRequest(graphPath: "me",
parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email, gender"])
.startWithCompletionHandler({ (connection, result, error) -> Void in
})

//MARK: - Functions Fb Logic
func signInWithFacebook()
{
if (FBSDKAccessToken.currentAccessToken() != nil) {
// User is already logged in, do work such as go to next view controller.
print("already logged in ")
returnUserData()
return
}
let faceBookLoginManger = FBSDKLoginManager()
faceBookLoginManger.logInWithReadPermissions(["public_profile", "email"], fromViewController:nil, handler: { (result, error)-> Void in
//result is FBSDKLoginManagerLoginResult
if (error != nil) {
print("error is \(error)")
} else if (result.isCancelled) {
//handle cancelations
} else if result.grantedPermissions.contains("email") {
self.returnUserData()
}
})
}
func returnUserData() {
if((FBSDKAccessToken.currentAccessToken()) != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, email"]).startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil) {
// Process error
print("Error: \(error)")
} else {
let accessToken = FBSDKAccessToken.currentAccessToken().tokenString
print("the access token is \(accessToken)")
let userID = result.valueForKey("id") as! NSString
let facebookProfileUrl = "http://graph.facebook.com/\(userID)/picture?type=large"
print("facebookProfileUrl: \(facebookProfileUrl)")
print("fetched user: \(result)")
}
})
}
}

Related

Get facebook user birthday and phone number

let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
fbLoginManager.logInWithReadPermissions(["email"], fromViewController: self) { (result, error) -> Void in
if (error == nil){
let fbloginresult : FBSDKLoginManagerLoginResult = result
if (fbloginresult.grantedPermissions != nil){
if(fbloginresult.grantedPermissions.contains("email"))
{
self.getFBUserData()
}
}
}
func getFBUserData(){
if((FBSDKAccessToken.currentAccessToken()) != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email, gender, user_birthday, phone"]).startWithCompletionHandler({ (connection, result, error) -> Void in
if (error == nil){
//everything works print the user data
print(result)
}
})
}
}
I am trying to get facebook user profile details.
i am not getting birthday date and phone when i try to access it
How to change my code to get user's birthday date.
any help will be appreciated.thanks in advance
Make this change in ur code
func getFBUserData(){
if((FBSDKAccessToken.currentAccessToken()) != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email, gender, birthday, phone"]).startWithCompletionHandler({ (connection, result, error) -> Void in
if (error == nil){
//everything works print the user data
print(result)
}
})
}
}
And in Permissions array add
#"user_birthday"
Facebook provide 3 permission email, user_friends and public_profile for that you dont need to put your app in facebook review. remain all you need to put your app for the review at developer.facebook.com
Here are all about permission:
https://developers.facebook.com/docs/facebook-login/permissions
Facebook clearly said:
let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
fbLoginManager.logInWithReadPermissions(["email"], fromViewController: self) { (result, error) -> Void in
if (error == nil){
let fbloginresult : FBSDKLoginManagerLoginResult = result
if (fbloginresult.grantedPermissions != nil){
if(fbloginresult.grantedPermissions.contains("email"))
{
self.getFBUserData()
}
}
#23/10/2002

Unable get Facebook User_birthday, Location in Swift2

Below is my code :-
let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
fbLoginManager .logInWithReadPermissions(["public_profile","user_birthday","email"], handler: { (result, error) -> Void in
if (error == nil)
{
let fbloginresult : FBSDKLoginManagerLoginResult = result
if(fbloginresult.grantedPermissions.contains("email"))
{
self.getFBUserData()
}
}
})
}
func getFBUserData()
{
if((FBSDKAccessToken.currentAccessToken()) != nil)
{
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture, email, gender, age_range, birthday"]).startWithCompletionHandler({ (connection, result, error) -> Void in
if (error == nil)
{
print(result)
self.performSegueWithIdentifier("login_with_facebook_vc", sender: nil)
}
})
}
}
I am new in swift2. So i am unable to get facebook user_birthday, location.
Please help me.
I use this code to get email:
func getEmail() {
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"email"])
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil)
{
// Process error
print("Error: \(error)")
}
else
{
print("fetched user: \(result)")
if let facebookEmail: String = result.valueForKey("email") as? String {
print("email is: \(facebookEmail)")
self.email = facebookEmail
}
}
})
}
Try this with birthday

Swift can't get Facebook username

I use the lastest Facebook SDK in swift. My problem is when I try to pass my Facebook name into a variable. There is my code :
func returnUserData()
{
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil)
{
// Process error
println("Error: \(error)")
}
else
{
// This variable is declared under my class declaration
self.userFacebook = result.valueForKey("name") as! String
println(self.userFacebook) //it's works, my Facebook name appear
}
})
}
But, when I try to use my variable "userFacebook" outsite of this function (returnUserData), the result is "nil".
I don't understand why my variable is set only in the function and not in my class.
Thanks
You pass parameter request what data is get for example get name.
request parameter like this
["fields": "id, name, first_name, last_name, picture.type(large), email"]
Try this code :
#IBAction func btnFBLoginPressed(sender: AnyObject) {
var fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
fbLoginManager .logInWithReadPermissions(["email"], handler: { (result, error) -> Void in
if (error == nil){
var fbloginresult : FBSDKLoginManagerLoginResult = result
if(fbloginresult.grantedPermissions.contains("email"))
{
self.getFBUserData()
fbLoginManager.logOut()
}
}
})
}
func getFBUserData(){
if((FBSDKAccessToken.currentAccessToken()) != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).startWithCompletionHandler({ (connection, result, error) -> Void in
if (error == nil){
println(result)
println(result["name"])
}
})
}
}

iOS facebookSDK get user full details

Iam using the last FBSDK (using swift)
// MARK: sign in with facebook
func signInWithFacebook()
{
if (FBSDKAccessToken.currentAccessToken() != nil)
{
// User is already logged in, do work such as go to next view controller.
println("already logged in ")
self.returnUserData()
return
}
var faceBookLoginManger = FBSDKLoginManager()
faceBookLoginManger.logInWithReadPermissions(["public_profile", "email", "user_friends"], handler: { (result, error)-> Void in
//result is FBSDKLoginManagerLoginResult
if (error != nil)
{
println("error is \(error)")
}
if (result.isCancelled)
{
//handle cancelations
}
if result.grantedPermissions.contains("email")
{
self.returnUserData()
}
})
}
func returnUserData()
{
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil)
{
// Process error
println("Error: \(error)")
}
else
{
println("the access token is \(FBSDKAccessToken.currentAccessToken().tokenString)")
var accessToken = FBSDKAccessToken.currentAccessToken().tokenString
var userID = result.valueForKey("id") as! NSString
var facebookProfileUrl = "http://graph.facebook.com/\(userID)/picture?type=large"
println("fetched user: \(result)")
}
when I print the fetched user I get only the id and the name ! ,
but i requested a permission for email and friends and profile ,
what's wrong ???
BTW : I moved this project from my macbook to another macbook ( because I formatted mine) it worked very well when it was at the the macbook which I created the project on , but after moving the project (using bitbucket clone) I got this results .
As per the new Facebook SDK, you must have to pass the parameters with the FBSDKGraphRequest
if((FBSDKAccessToken.currentAccessToken()) != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, email"]).startWithCompletionHandler({ (connection, result, error) -> Void in
if (error == nil){
println(result)
}
})
}
Documentations Link : https://developers.facebook.com/docs/facebook-login/permissions/v2.4
User object reference : https://developers.facebook.com/docs/graph-api/reference/user
With public profile you can get gender :
public_profile (Default)
Provides access to a subset of items that are part of a person's public profile. A person's public profile refers to the following properties on the user object by default:
id
name
first_name
last_name
age_range
link
gender
locale
timezone
updated_time
verified
Swift 4
An example in Swift 4 that also shows how to correctly parse out the individual fields from the result:
func fetchFacebookFields() {
//do login with permissions for email and public profile
FBSDKLoginManager().logIn(withReadPermissions: ["email","public_profile"], from: nil) {
(result, error) -> Void in
//if we have an error display it and abort
if let error = error {
log.error(error.localizedDescription)
return
}
//make sure we have a result, otherwise abort
guard let result = result else { return }
//if cancelled nothing todo
if result.isCancelled { return }
else {
//login successfull, now request the fields we like to have in this case first name and last name
FBSDKGraphRequest(graphPath: "me", parameters: ["fields" : "first_name, last_name"]).start() {
(connection, result, error) in
//if we have an error display it and abort
if let error = error {
log.error(error.localizedDescription)
return
}
//parse the fields out of the result
if
let fields = result as? [String:Any],
let firstName = fields["first_name"] as? String,
let lastName = fields["last_name"] as? String
{
log.debug("firstName -> \(firstName)")
log.debug("lastName -> \(lastName)")
}
}
}
}
}
I guess this code should help you get the required details
Swift 2.x
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil)
{
// Process error
print("Error: \(error)")
}
else
{
print("fetched user: \(result)")
let userName : NSString = result.valueForKey("name") as! NSString
print("User Name is: \(userName)")
let userID : NSString = result.valueForKey("id") as! NSString
print("User Email is: \(userID)")
}
})
In Swift 4.2 and 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.authenticationToken)
print(accessToken.grantedPermissions!)
print(accessToken.expirationDate)
print(accessToken.declinedPermissions!)
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

Graph request returns nil after login

I am using facebook ios sdk 4.1
And i am using this code to get user's info after user click button and login
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil)
{
println("Error: \(error)")
}
else
{
var fbuseremail = result.valueForKey("email") as! NSString
var fbfirstname = result.valueForKey("first_name") as! NSString
var fblastname = result.valueForKey("last_name") as! NSString
var fbusername = result.valueForKey("name") as! NSString
//....more code
But result.valueForKey("email") and others returns nil
Any idea how to fix this ?
Get user info in facebook sdk 4.x swift
#IBAction func btnFBLoginPressed(sender: AnyObject) {
var fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
fbLoginManager .logInWithReadPermissions(["email"], handler: { (result, error) -> Void in
if (error == nil){
var fbloginresult : FBSDKLoginManagerLoginResult = result
if(fbloginresult.grantedPermissions.containsObject("email"))
{
self.getFBUserData()
fbLoginManager.logOut()
}
}
})
}
func getFBUserData(){
if((FBSDKAccessToken.currentAccessToken()) != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).startWithCompletionHandler({ (connection, result, error) -> Void in
if (error == nil){
println(result)
}
})
}
}
Output :
{
email = "ashishkakkad8#gmail.com";
"first_name" = Ashish;
id = 910855688971343;
"last_name" = Kakkad;
name = "Ashish Kakkad";
picture = {
data = {
"is_silhouette" = 0;
url = "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpf1/v/t1.0-1/p200x200/10394859_900936369963275_5557870055628103117_n.jpg?oh=fefbfca1272966fc78286c36741f9ac6&oe=55C89225&__gda__=1438608579_9133f15e55b594f6ac2306d61fa6b6b3";
};
};
}

Resources