How to fetch complete userDetails from the Facebook API
- (void)viewDidLoad {
[super viewDidLoad];
// Uncomment to automatically sign in the user.
_signInFacebook.delegate = self;
_signInFacebook.readPermissions = #[#"email",#"birthday"];
}
- (void) loginButton:(FBSDKLoginButton *)loginButton
didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result
error:(NSError *)error{
NSLog(#"LOGGED IN TO FACEBOOK");
[self fetchUserInfo];
}
-(void)fetchUserInfo {
FBSDKAccessToken* token = [FBSDKAccessToken currentAccessToken];
[[[FBSDKGraphRequest alloc] initWithGraphPath:[NSString stringWithFormat:#"/%#",token.userID] parameters:#{ #"fields":#"id,name,first_name,middle_name,last_name,email,gender,location,picture.type(large),age_range,verified,birthday"} HTTPMethod:#"GET"]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"fetched user:%#", result);
if ([result isKindOfClass:[NSDictionary class]])
{
NSLog(#"%#",result);
[USERDEFAULTS setObject:result forKey:PROFILE_KEY];
}
}
else
{
NSLog(#"Error fetchUserInfo %#",error);
}
}];
}
Expecting mobile number to fetch from facebook API
You should use "picture" instead of "photo" to get user profile photo.
And you can get userID form the accessToken like:
FBSDKAccessToken* token = [FBSDKAccessToken currentAccessToken];
NSString *ID = token.userID
When log in:
To get birthday, you need permission "user_birthday"
To get location, you need permission "user_location"
You can test everything in Facebook Graph API Explorer before implementing in your app.
To request for permission when logging in, sample code:
FBSDKLoginManager* login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions:#[#"public_profile",#"email",#"user_birthday"] fromViewController:self handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
//your code to handle login result
}];
I have followed the custom UI FBLogin button for my app.In LoginHomeViewController I have the FBLogin button.
Here is code which I am using in ViewDidLoad
FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init];
loginButton.readPermissions = #[#"public_profile", #"email", #"user_friends"];
if ([FBSDKAccessToken currentAccessToken])
{
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:nil] startWithCompletionHandler: ^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error)
{
NSLog(#"fetched user:%#", result);
}
}];
}
1) The issue is When first time there is no console output on safari or FB I am logging in I want user details in this view controller i.e. LoginHomeViewController.
2) Currently Once login done in safari or FB, when I goes back to previous view and enter into this controller i.e. LoginHomeViewController then am getting user details in
NSLog(#"fetched user:%#", result);
I tried above code in Custom log in button click i.e.
- (IBAction)facebookClcik:(id)sender {
}
But am facing same issue.
Following are my AppDelegate methods
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions : (NSDictionary *)launchOptions
{
[FBSDKLoginButton class];
return [[FBSDKApplicationDelegate sharedInstance] application : application didFinishLaunchingWithOptions : launchOptions];
}
- (BOOL)application : (UIApplication *)application openURL : (NSURL *)url sourceApplication : (NSString *)sourceApplication annotation : (id)annotation
{
return [[FBSDKApplicationDelegate sharedInstance] application : application openURL : url sourceApplication : sourceApplication annotation : annotation];
}
- (void)applicationDidBecomeActive : (UIApplication *)application
{
[FBSDKAppEvents activateApp];
}
Hope this way helps you to retrieve user details:
- (IBAction)facebookLoginBtn:(id)sender {
appDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
appDelegate.logOut= true;
FBSession *session = [[FBSession alloc] initWithPermissions:#[#"publish_actions",#"email"]];
[FBSession setActiveSession:session];
[session openWithBehavior:FBSessionLoginBehaviorForcingWebView
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
if (FBSession.activeSession.isOpen) {
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
NSLog(#"accesstoken %#",[NSString stringWithFormat:#"%#",session.accessTokenData]);
NSLog(#"user id %#",user.id);
NSLog(#"Email %#",[user objectForKey:#"email"]);
NSLog(#"User Name %#",user.first_name);
appDelegate.UserName=[NSMutableString stringWithFormat:#"%#", user.first_name];
appDelegate.firstname =[NSMutableString stringWithFormat:#"%#", user.first_name];
appDelegate.idStr= user.id;
UserEmailStr= [user objectForKey:#"email"];
// [self fetchGuestuser];
}
}];
}
}];
}
If you navigate user to safari, Apple may reject your app
for more refer this
try this code
if ([FBSDKAccessToken currentAccessToken])
{
NSLog(#"Token is available");
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:#{#"fields": #"id,name,link,first_name, last_name, picture.type(large), email, birthday, bio ,location ,friends ,hometown , friendlists"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error)
{
FbId = [NSString stringWithFormat:#"%#",[result objectForKey:#"id"]];
firstName = [NSString stringWithFormat:#"%#",[result objectForKey:#"first_name"]];
lastName = [NSString stringWithFormat:#"%#",[result objectForKey:#"last_name"]];
UserName = [NSString stringWithFormat:#"%#",[result objectForKey:#"name"]];
email_id = [NSString stringWithFormat:#"%#",[result objectForKey:#"email"]];
picture = [NSString stringWithFormat:#"%#",[[[result objectForKey:#"picture"] objectForKey:#"data"] objectForKey:#"url"]];
Password = [NSString stringWithFormat:#"%#",[result objectForKey:#"email"]];
// user_id=[NSString stringWithFormat:#"%#",[result objectForKey:#"id"]];
NSLog(#"email is %#", [result objectForKey:#"email"]);
NSLog(#"picture is %#", picture);// [result objectForKey:#"picture"]
[[NSUserDefaults standardUserDefaults]setObject:result forKey:#"FBData"];
[[NSUserDefaults standardUserDefaults]setObject:#"Yes" forKey:#"Check"];
[self fbLoginParseData];
}
else
{
NSLog(#"Error %#",error);
}
}];
}
else
{
NSLog(#"User is not Logged in");
}
I use facebook sdk on my iOS app to sign-in and sharing story.
Sharing story on Facebook feature was working properly but today it's not working. I don't know why it's not working because no code changes related to that feature.
The followings are the code that requests publish_actions permission.
// Request publish_actions
[FBSession.activeSession requestNewPublishPermissions:[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound) {
// Permission not granted, tell the user we will not publish
} else {
// Permission granted
}
} else {
NSLog(#"DEBUG: error = %#", error);
// There was an error, handle it
// See https://developers.facebook.com/docs/ios/errors/
}
}];
The error message is as followings,
Domain=com.facebook.sdk Code=2 "The operation couldn’t be completed. com.facebook.sdk:ErrorReauthorizeFailedReasonSessionClosed"
UserInfo=0xXXXXXXXXX {
com.facebook.sdk:ErrorLoginFailedReason=
com.facebook.sdk:ErrorReauthorizeFailedReasonSessionClosed,
NSLocalizedFailureReason=
com.facebook.sdk:ErrorReauthorizeFailedReasonSessionClosed,
com.facebook.sdk:ErrorSessionKey= ... >
}
If anybody knows this, please help me.
** Facebook SDK version is 3.18, and publish_actions item is already approved in developer.facebook.com
You can use FBSDKAccessToken
if ([[FBSDKAccessToken currentAccessToken] hasGranted:#"publish_actions"]) {
[self doShare];
} else {
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithPublishPermissions:#[#"publish_actions"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
// Process error
} else if (result.isCancelled) {
// Handle cancellations
} else {
// If you ask for multiple permissions at once, you
// should check if specific permissions missing
if ([result.grantedPermissions containsObject:#"publish_actions"]) {
// Do work
[self doShare];
}
}
}];
}
where doShare
-(void) doShare{
NSString *url = [NSString stringWithFormat:#"http://example.com/locations/%d",1];
NSDictionary *properties = #{
#"your action" :url
};
[[[FBSDKGraphRequest alloc]
initWithGraphPath:#"me/example-staging:something"
parameters: properties
HTTPMethod:#"POST"]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
// NSLog(#"Post id:%#", result[#"id"]);
}
}];
- (void)viewDidLoad
{
[super viewDidLoad];
m_allFriends = [[NSMutableArray alloc] init];
if ([[FBSession activeSession] isOpen])
{
if ([[[FBSession activeSession] permissions]indexOfObject:#"user_friends"] == NSNotFound)
{
[[FBSession activeSession] requestNewPublishPermissions:[NSArray arrayWithObject:#"user_friends"] defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session,NSError *error){
[self getFBFriendListFunc];
NSLog(#"1");
}];
}
else
{
[self getFBFriendListFunc];
NSLog(#"2");
}
}
else
{
[FBSession openActiveSessionWithPublishPermissions:[NSArray arrayWithObject:#"user_friends"]
defaultAudience:FBSessionDefaultAudienceOnlyMe
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if (!error && status == FBSessionStateOpen) {
[self getFBFriendListFunc];
NSLog(#"3");
}else{
NSLog(#"error");
}
}];
}
}
-(void)getFBFriendListFunc
{
[FBRequestConnection startWithGraphPath:#"me/friends"
parameters:nil
HTTPMethod:#"GET"
completionHandler:^(
FBRequestConnection *connection,
id result,
NSError *error
) {
NSLog(#"me/friends result=%#",result);
NSLog(#"me/friends error = %#", error.description);
NSArray *friendList = [result objectForKey:#"data"];
[m_allFriends addObjectsFromArray: friendList];
}];
}
I try to connect Facebook with their API, actually this code connect Facebook, Facebook ask me this application want to use your information than i confirmed. Last step, Facebook return again my application than this getFBFriendListFunc should be run but none of if/else work. Nothing display...
I get this codes on Facebook developer which code part wrong ?
Any idea ?
Thank you...
For inviting users you can use the following code after adding the facebook-sdk
[FBWebDialogs
presentRequestsDialogModallyWithSession:sharedFacebookHelper.session
message:#"Your invite message"
title:nil
parameters:nil
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
// An error occurred, we need to handle the error
// See: https://developers.facebook.com/docs/ios/errors
NSLog(#"Error publishing story: %#", error.description);
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
// User canceled.
NSLog(#"User cancelled.");
} else {
// Handle the publish feed callback
}
}
}];
I add this function on AppDelegate.m if this function does not exit login session never be work i hope this code help any one :)
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
BOOL wasHandled = [FBAppCall handleOpenURL:url sourceApplication:sourceApplication];
return wasHandled;
}
The code I have used
if (FBSession.activeSession.state == FBSessionStateOpen
|| FBSession.activeSession.state == FBSessionStateOpenTokenExtended) {
// Close the session and remove the access token from the cache
// The session state handler (in the app delegate) will be called automatically
[FBSession.activeSession closeAndClearTokenInformation];
// If the session state is not any of the two "open" states when the button is clicked
} else {
// Open a session showing the user the login UI
// You must ALWAYS ask for basic_info permissions when opening a session
[FBSession openActiveSessionWithReadPermissions:#[#"basic_info,email"]
allowLoginUI:YES
completionHandler:
^(FBSession *session, FBSessionState state, NSError *error) {
// Retrieve the app delegate
AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
// Call the app delegate's sessionStateChanged:state:error method to handle session state changes
[appDelegate sessionStateChanged:session state:state error:error];
}];
}
from this code i need to get user name and mail id. if any one know the solution please help me thanks in advance.
if ([FBSDKAccessToken currentAccessToken]) {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:#{#"fields": #"email,name,first_name"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"fetched user:%#", result);
NSLog(#"%#",result[#"email"]);
}
}];
}
Use the Following Code
FBSession *session = [[FBSession alloc] initWithPermissions:#[#"basic_info", #"email"]];
[FBSession setActiveSession:session];
[session openWithBehavior:FBSessionLoginBehaviorForcingWebView
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
if (FBSession.activeSession.isOpen) {
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
NSLog(#"accesstoken %#",[NSString stringWithFormat:#"%#",session.accessTokenData]);
NSLog(#"user id %#",user.id);
NSLog(#"Email %#",[user objectForKey:#"email"]);
NSLog(#"User Name %#",user.username);
}
}];
}
}];
for new code facebook SDK ver 4.0 and above
see this link
below
// use facebook SDK 3.8
add the following methods in AppDelegate.m
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication: (NSString *)sourceApplication annotation:(id)annotation
{
return [FBAppCall handleOpenURL:url sourceApplication:sourceApplication fallbackHandler:^(FBAppCall *call)
{
NSLog(#"Facebook handler");
}
];
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[FBAppEvents activateApp];
[FBAppCall handleDidBecomeActive];
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application
{
[FBSession.activeSession close];
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
se the follwing code in your viewcontroler .h
#import <UIKit/UIKit.h>
#import <FacebookSDK/FacebookSDK.h>
#import <CoreLocation/CoreLocation.h>
#interface ViewController : UIViewController<FBLoginViewDelegate>
#property (strong, nonatomic) IBOutlet UILabel *lblUserName;
#property (strong, nonatomic) IBOutlet UITextField *txtEmailId;
#property (strong, nonatomic) IBOutlet UIButton *lblCreate;
#property (strong, nonatomic) IBOutlet FBProfilePictureView *profilePic;
#property (strong, nonatomic) id<FBGraphUser> loggedInUser;
- (IBAction)butCreate:(id)sender;
- (void)showAlert:(NSString *)message
result:(id)result
error:(NSError *)error;
#end
// apply the below code to your view controller.m
- (void)viewDidLoad
{
[super viewDidLoad];
FBLoginView *loginview=[[FBLoginView alloc]initWithReadPermissions:#[#"email",#"user_likes"]];
loginview.frame=CGRectMake(60, 50, 200, 50);
loginview.delegate=self;
[loginview sizeToFit];
[self.view addSubview:loginview];
}
-(void)loginViewShowingLoggedInUser:(FBLoginView *)loginView
{
self.lblCreate.enabled=YES;
self.txtEmailId.enabled=YES;
self.lblUserName.enabled=YES;
}
-(void)loginViewFetchedUserInfo:(FBLoginView *)loginView user:(id<FBGraphUser>)user
{
self.lblUserName.text=[NSString stringWithFormat:#"%#",user.name];
self.txtEmailId.text=[user objectForKey:#"email"];
//self.profilePic.profileID=user.id;
self.loggedInUser=user;
}
-(void)loginViewShowingLoggedOutUser:(FBLoginView *)loginView
{
self.txtEmailId.text=nil;
self.lblUserName.text=nil;
self.loggedInUser=nil;
self.lblCreate.enabled=NO;
}
-(void)loginView:(FBLoginView *)loginView handleError:(NSError *)error{
NSLog(#"Show the Error ==%#",error);
}
Swift 1.2 & above
Create a dictionary :
class ViewController: UIViewController {
var dict : NSDictionary!
}
Fetching the data :
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){
self.dict = result as NSDictionary
println(self.dict)
NSLog(self.dict.objectForKey("picture")?.objectForKey("data")?.objectForKey("url") as String)
}
})
}
Output should be :
{
email = "karthik.saral#gmail.com";
"first_name" = Karthi;
id = 924483474253864;
"last_name" = keyan;
name = "karthi keyan";
picture = {
data = {
"is_silhouette" = 0;
url = "XXXXXXX";
};
};
}
Make the following request after successfully login in, you don't read publish_actions permissions for it.
/* make the API call */
[FBRequestConnection startWithGraphPath:#"/me"
parameters:nil
HTTPMethod:#"GET"
completionHandler:^(
FBRequestConnection *connection,
id result,
NSError *error
) {
/* handle the result */
}];
follow this link: https://developers.facebook.com/docs/graph-api/reference/user
You can get these information by using the NSDictionary: NSDictionary<FBGraphUser> *user,
you just need to use objectforkey to access these values like :
[user objectForKey:#"id"],
[user objectForKey:#"username"],
[user objectForKey:#"email"].
Hopefully it will work for you.
This currently works with the latest version of the FB SDK:
Somewhere before set up the FB login button correctly (assuming self.facebookLoginButton is initialized via IB):
self.facebookLoginButton.readPermissions = #[#"public_profile", #"email"];
self.facebookLoginButton.delegate = self;
Then in loginButton:didCompleteWithResult:error::
- (void)loginButton:(FBSDKLoginButton *)loginButton
didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result
error:(NSError *)error
{
NSDictionary *parameters = #{#"fields":#"email,name"};
FBSDKGraphRequest *graphRequest = [[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:parameters];
[graphRequest startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error)
{
LogInfo(#"fetched user:%#", result);
}];
}
Here is the reference page that helped: https://developers.facebook.com/docs/graph-api/reference/user
The username field of the User object has been removed, and does not exist in Graph API v2.0. In v2.0 of the API is there is no way to get the FB username of a user.you can use app scope id though as username.
Facebook got rid of the username because the username is one way of sending emails via Facebook.
For example, given the url http://www.facebook.com/sebastian.trug
the corresponding Facebook email would be sebastian.trug#facebook.com
which, if emailed, would be received to messages directly (if the message setting is set to public), otherwise to the other inbox.
Source: https://developers.facebook.com/docs/apps/changelog#v2_0_graph_api
here is the code for swift 3.0
let graphRequest:FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me",
parameters: ["fields":"first_name,email, picture.type(large)"])
graphRequest.start(completionHandler: { (connection, result,
error) -> Void in
if ((error) != nil)
{
print("Error: \(error)")
}
else
{
let data:[String:AnyObject] = result as! [String : AnyObject]
print(data)
}
})
[FBRequestConnection startWithGraphPath:#"/me"
parameters:nil
HTTPMethod:#"GET"
completionHandler:^(
FBRequestConnection *connection,
NSDictionary *result,
NSError *error
) {
/* handle the result */
_fbId = [result objectForKey:#"id"];
_fbName = [result objectForKey:#"name"];
_fbEmail = [result objectForKey:#"email"];
NSLog(#"%#",_fbId);
NSLog(#"%#",_fbName);
NSLog(#"%#",_fbEmail);
}];
use this code:
FBSession *session = [[FBSession alloc] initWithPermissions:#[#"public_profile"]];
[FBSession setActiveSession:session];
[session openWithBehavior:FBSessionLoginBehaviorForcingWebView
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
if (FBSession.activeSession.isOpen)
{
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error)
{
if (!error)
{
NSLog(#"%#", user);
[[[UIAlertView alloc] initWithTitle:#"welcome"
message:[NSString stringWithFormat:#"%#\n%#\n%#\n%#\n%#\n%#",
user[#"name"],
user[#"gender"],
user[#"id"],
user[#"link"],
user[#"email"],
user[#"timezone"]]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil]
show];
}
}];
}
}];
facebook ios sdk get user name and email 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")
}
})
Xcode 8.2.1 and Objective-C
Getting login information any of the place after killing the app
FBRequest *friendRequest = [FBRequest requestForGraphPath:#"me/?fields=name,picture,birthday,email,location"];
[friendRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
if(error == nil) {
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Facebook" message:#"Success in fetching Facebook information." delegate:self cancelButtonTitle:#"OK"otherButtonTitles:nil, nil];
[alert show];
}
else
{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Facebook" message:#"Problem in fetching Facebook Information. Try Later!" delegate:self cancelButtonTitle:#"OK"otherButtonTitles:nil, nil];
[alert show];
}
}];
First you have to get access permission for your App through GraphAPI.
Create a NSMutableDictionary with objectandKey.
Your object will be the value which you are reciveing for example your name and your emailId.
Code snippet:
NSMutableDictionary *params=[[NSMutableDictionary alloc]init];
[params setObject:nameStr forKey:#"name"];
[params setObject:emailStr forKey:#"email"];