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"];
Related
I've custom button if created in storyboard and connected to my ViewController :
#property (strong, nonatomic) IBOutlet UIButton *FBConnectButton;
This button has an action:
- (IBAction)FBConnectAction:(id)sender {
//
NSLog(#"SDK: Facebook iOS SDK Login");
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login
logInWithReadPermissions: #[#"public_profile", #"email", #"user_friends"]
fromViewController:self
handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
NSLog(#"Process error");
} else if (result.isCancelled) {
NSLog(#"Cancelled");
} else {
NSLog(#"Logged in");
}
}];
}
There is too delegate for login to return the result :
-(void)loginButton:(FBSDKLoginButton *)loginButton didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result error:(NSError *)error{
NSLog(#"%#",result);
}
-(void)loginButtonDidLogOut:(FBSDKLoginButton *)loginButton{
}
How do i say to my UIButton and set its delegate to FBSDKLoginButton, so after login it returns login data ?
The didCompleteWithResult and loginButtonDidLogOut delegate methods are for the FBSDKLoginButton which is not the same as custom login. For custom login you already have the callback block handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {...} where you should expect the results.
Once you get back the results in the callback block, you can check if the user has granted the permissions that you have asked for. e.g. for email:
if ([result.grantedPermissions containsObject:#"email"]) {
NSLog(#"Email permission granted.");
[self makeGraphAPICall];
}
Once you know you have the permissions, make a Graph API call to get the required data, something like:
- (void)makeGraphAPICall {
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"/me?fields=id,name,email"
parameters:nil
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
NSLog(#"Required User Data: %#", result);
}];
}
Also, if you require permissions that need review and approval, make sure you are testing this with an admin/developer of the app.
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've successfully use facebook SDK to login and get profile picture and name. But It's in the same view. I'm wondering how to change to another view after login.
AppDelegate.m file
- (void)applicationDidBecomeActive:(UIApplication *)application {
[[FBSession activeSession] handleDidBecomeActive];
}
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
return [[FBSession activeSession]handleOpenURL:url];
}
viewController.m file
#interface loginViewController () <FBLoginViewDelegate>
#property (weak, nonatomic) IBOutlet FBLoginView *loginView;
#property (weak, nonatomic) IBOutlet FBProfilePictureView *ProfilePic;
#property (weak, nonatomic) IBOutlet UILabel *ProfileName;
- (void)viewDidLoad {
[super viewDidLoad];
self.loginView.delegate = self;
}
#pragma mark FBLoginviewDelegate
-(void)loginViewFetchedUserInfo:(FBLoginView *)loginView user:(id<FBGraphUser>)user{
self.ProfilePic.profileID = user.objectID;
self.ProfileName.text = user.name;
}
-(void)loginViewShowingLoggedOutUser:(FBLoginView *)loginView{
self.ProfilePic.profileID = nil;
self.ProfileName.text = nil;
}
this is custom button method :
- (void)viewDidLoad {
[super viewDidLoad];
// self.loginView.delegate = self; //hide one
}
- (IBAction)butFacebooklogin:(id)sender
{
NSArray *permissions = #[#"email",#"user_about_me",#"user_status",#"user_location"];
// OPEN Session!
[FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
// if login fails for any reason, we alert
if (error) {
//NSLog(#"error %#",error);
// show error to user.
} else if (FB_ISSESSIONOPENWITHSTATE(status)) {
// no error, so we proceed with requesting user details of current facebook session.
//NSLog(#"we are here");
//NSLog(#"----%#",[session accessTokenData].accessToken);
// NSString *tok = [session accessTokenData].accessToken;
// NSLog(#"tok 2");
[[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (error) {
NSLog(#"error:%#",error);
}
else
{
/*
NSString *userlocation=[NSString stringWithFormat:#"%#",user.location[#"name"]];
NSArray *items = [userlocation componentsSeparatedByString:#","];
NSString *usercity, *userstate;
if ([items count]>0) {
usercity=[items objectAtIndex:0];
userstate=[items objectAtIndex:1];
userstate = [userstate stringByReplacingOccurrencesOfString:#" " withString:#""];
}
else
{
usercity=#"";
userstate=#"";
}
*/
NSString *email=[user objectForKey:#"email"];
if (email.length>0) {
email=[user objectForKey:#"email"];
}
else
{
email=#"";
}
NSString *userUpdate =[NSString stringWithFormat:#"user_id=%#&fname=%#&lname=%#",email,user.first_name,user.last_name,nil];
NSLog(#" RequestString for get login details: %#",userUpdate);
// here add ur segue or push view method
}
}];
// [self promptUserWithAccountName]; // a custom method - see below:
}
}];
}
In latest FB SDK this doesn't work anymore. FBSession (along with FBRequest) class has been dropped.
Now you have to use FBSDKLoginManager class and its method
- (void)logInWithReadPermissions:(NSArray *)permissions handler:(FBSDKLoginManagerRequestTokenHandler)handler;
Sample code of login and getting user info:
FBSDKLoginManager* lm = [[FBSDKLoginManager alloc] init];
[lm logInWithReadPermissions:#[#"public_profile", #"email"] fromViewController:self handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
// no error, so get user info
if (!error && !result.isCancelled)
{
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:nil]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"fetched user:%# and Email : %#", result,result[#"email"]);
}
}];
}
}];
As stated here
I tried over 2000 things to get the user's email. I can't get it from the Facebook SDK's graph API. It doesn't contain email property. I also tried to add manually the email property to the FB framework and nothing happened. Is it possible to download the first FB SDK which is compatible with iOS 7? Does it still have the email property, doesn't it? Or is there any other way how to get the REAL email, I must work with them. I don't need the example#facebook.com.
Thanks for any advice.
EDIT
NSArray *permissions = #[#"email", #"public_profile"];
[PFFacebookUtils logInWithPermissions:permissions block:^(PFUser *user, NSError *error) {
if (!user) {
if (!error) {
NSLog(#"The user cancelled the Facebook login.");
} else {
NSLog(#"An error occurred: %#", error.localizedDescription);
}
if ([delegate respondsToSelector:#selector(commsDidLogin:)]) {
[delegate commsDidLogin:NO];
}
} else {
if (user.isNew) {
NSLog(#"User signed up and logged in through Facebook!");
} else {
NSLog(#"User logged in through Facebook!");
}
[FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
PFUser *usere = [PFUser currentUser];
[usere setObject:[result objectForKey:#"first_name"] forKey:#"name"];
[usere setObject:[result objectForKey:#"last_name"] forKey:#"surname"];
// [usere setObject:[result objectForKey:#"email"] forKey:#"mail"];
[usere saveEventually];
NSLog(#"user info: %#", result);
}
}];
}
if ([delegate respondsToSelector:#selector(commsDidLogin:)]) {
[delegate commsDidLogin:YES];
}
}];
}
I have not code for graph API,
but with new facebook sdk version 3, I have code for that.
-(void)openFbSession
{
[[self appDelegate].session closeAndClearTokenInformation];
NSArray *permissions = [NSArray arrayWithObjects:#"email",#"user_location",#"user_birthday",#"user_hometown",nil];
[self appDelegate].session = [[FBSession alloc] initWithPermissions:permissions];
[[self appDelegate].session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
if(!error)
{
NSLog(#"success");
[self myFbInfo];
}
else
{
NSLog(#"failure");
}
}];
}
and for all information, myFbInfo method is
-(void)myFbInfo
{
[FBSession setActiveSession:[self appDelegate].session];
[[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *FBuser, NSError *error) {
if (error) {
// Handle error
}
else {
//NSString *userName = [FBuser name];
//NSString *userImageURL = [NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large", [FBuser id]];
NSLog(#"Name : %#",[FBuser name]);
NSLog(#"first name : %#",[FBuser first_name]);
NSLog(#"Last name : %#",[FBuser last_name]);
NSLog(#"ID : %#",[FBuser id]);
NSLog(#"username : %#",[FBuser username]);
NSLog(#"Email : %#",[FBuser objectForKey:#"email"]);
NSLog(#"user all info : %#",FBuser);
}
}];
}
EDIT
in appdelegate.h
#property (strong, nonatomic) FBSession *session;
in appdelegate.m
- (BOOL)application: (UIApplication *)application openURL: (NSURL *)url sourceApplication: (NSString *)sourceApplication annotation: (id)annotation
{
//NSLog(#"FB or Linkedin clicked");
return [self.session handleOpenURL:url];
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[FBSession.activeSession handleDidBecomeActive];
}
- (void)applicationWillTerminate:(UIApplication *)application
{
[self.session close];
}
You have to request permissions first, as descibed at https://developers.facebook.com/docs/facebook-login/ios/v2.0#button-permissions
After that, you can request the user's information: https://developers.facebook.com/docs/ios/graph#userinfo
You can't just get the user's email address, you must ask them for permission to do so. Take a look at this:
https://developers.facebook.com/docs/facebook-login/permissions/v2.0
Facebook Connect will allow the passing of scope=email in the get string of your auth call.
I could not get it to work with above examples. I solved it using a more complex call to FBSDKGraphRequest..
In viewDidLoad:
if(FBSDKAccessToken.currentAccessToken() != nil) {
println("Logged in to FB")
self.returnUserData() //Specified here below
} else {
print("Not logged in to FB")
let loginView : FBSDKLoginButton = FBSDKLoginButton()
loginView.center = self.view.center
loginView.readPermissions = ["public_profile", "email", "user_friends"]
loginView.delegate = self
self.view.addSubview(loginView)
}
}
Read permissions above is important to be able to get it later on when you request from FB server.
Remember to conform to the "FBSDKLoginButtonDelegate" protocols by including the functions needed (not included here).
To be able to fetch email etc. I use the more complex call for the graphRequest and specify the accesstoken and the parameters (se below).
let fbAccessToken = FBSDKAccessToken.currentAccessToken().tokenString
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(
graphPath: "me",
parameters: ["fields":"email,name"],
tokenString: fbAccessToken,
version: nil,
HTTPMethod: "GET")
... and in the same function execute with completionHandler:
graphRequest.startWithCompletionHandler({ (connection, result, error) -> () in result
if ((error) != nil) {
// Process error
println("Error: \(error)")
} else {
println("fetched user: \(result)")
}
}
Works beautifully!
And additionally.. parameters are found listed here:
https://developers.facebook.com/docs/graph-api/reference/v2.2/user
if ([result.grantedPermissions containsObject:#"email"]) {
// Do work
NSLog(#"%#",[FBSDKAccessToken currentAccessToken]);
if ([FBSDKAccessToken currentAccessToken]) {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"/me" parameters:[NSMutableDictionary dictionaryWithObject:#"picture.type(large),id,email,name,gender" forKey:#"fields"] tokenString:result.token.tokenString version:nil HTTPMethod:#"GET"]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"fetched user:%#", result);
}
}];
}
}
In the "old" FB iOS SDK I could receive user information via the following:
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"SELECT uid, name, email, pic FROM user WHERE uid=me()", #"query",
nil];
JBFacebookManager *fbManager = [JBFacebookManager getInstance];
fbManager.requestDelegate = self;
[fbManager.facebook requestWithMethodName:#"fql.query"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
How can I do this with the new FB iOS SDK 3.0? Do I need to use FBRequest or FBOpenGraphAction or FBGraphObject or a combination of those or something completely different?
if (FBSession.activeSession.isOpen) {
[[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
self.nameLabel.text = user.name;
self.emailLabel.text = [user objectForKey:#"email"];
}
}];
}
Because FBGraphUser doesn't have an email #property, we can't access the information like with the name (dot-syntax), however the NSDictionary still has the email kv-pair and we can access it like we would do with a normal NSDictionary.
Don't forget to ask for the email permission though:
NSArray *permissions = [[NSArray alloc] initWithObjects:#"email", nil];
[FBSession sessionOpenWithPermissions:permissions completionHandler:
^(FBSession *session, FBSessionState state, NSError *error) {
[self facebookSessionStateChanged:session state:state error:error];
}];
Once you have access to (id<FBGraphUser>)user, you could simply use, user[#"email"].
from this we can get facebook user's basic info and email id.
[FBSession openActiveSessionWithReadPermissions:#[#"basic_info",#"email"] allowLoginUI:YES completionHandler:^(FBSession *session,FBSessionState status,NSError *error){
if(error)
{
NSLog(#"Facebook Error : %#",error.localizedDescription);
}
else{
}
// Respond to session state changes,
// ex: updating the view
}];
Did you read the source code of the 3.0 SDK? There is a method that I think is identical:
- (FBRequest*)requestWithMethodName:(NSString *)methodName
andParams:(NSMutableDictionary *)params
andHttpMethod:(NSString *)httpMethod
andDelegate:(id <FBRequestDelegate>)delegate;
The easiest method for getting the info after logging in is :
-(IBAction)loginWithFacebook:(id)sender{
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login
logInWithReadPermissions: #[#"public_profile",#"email"]
fromViewController:self
handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
NSLog(#"Process error");
} else if (result.isCancelled) {
NSLog(#"Cancelled");
} else {
NSLog(#"Logged in");
[self getFacebookProfileInfos];
}
}];
}
-(void)getFacebookProfileInfos {
NSDictionary *parameters = # {#"fields": #"id, name, first_name, last_name, picture.type(large), email"};
if ([FBSDKAccessToken currentAccessToken]) {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:parameters]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"fetched user:%#", result);
}
}];
}
}
You will get all the info the result.