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
}];
Related
I'm using Parse and Facebook for account management in my app. Whenever the user logs in through the facebook button, my code works perfectly because facebook sdk automatically generates a new access token. However, if I use an autologin code which checks whether user has already approved of the app, I have no access token and can't access facebook data for that user. I don't know how to request an access token for a user who has already agreed to use my app.
Loading data:
- (void)_loadData :(BOOL)updateData
{
NSLog(#"entered _loadData");
NSMutableDictionary* userInfoParams = [NSMutableDictionary dictionary];
[userInfoParams setValue:#"id,name,email,gender" forKey:#"fields"];
if([FBSDKAccessToken currentAccessToken])
{
NSLog(#"Expiration date of token: %#", [[FBSDKAccessToken currentAccessToken] expirationDate]);
}
else NSLog(#"No access token");
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:userInfoParams];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection* connection, id result, NSError* error)
{
if(!error)
{
...
}
}
}
Auto-login system:
(void)viewDidAppear:(BOOL)animated
{
if ([PFUser currentUser] || [PFFacebookUtils isLinkedWithUser:[PFUser currentUser]])
{
NSLog(#"Yes");
[self _loadData:YES];
[self transitionToLoginSegue:(id)self];
}
else NSLog(#"No");
}
Also, the access tokens I receive when user clicks through the log in button last for 4 weeks, so if there was a way to manually assign an access token then I could do that, however [FBSDKAccessToken currentAccessToken] is not assignable so I can't do that either.
This is my code below,
if ([self check_network])
{
START_LOAD;
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login
logInWithReadPermissions: #[#"public_profile",#"email",#"user_friends"]
fromViewController:self
handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
STOP_LOAD;
NSLog(#"Process error");
NSLog(#"%#",error);
TOAST_FOR_TRY_AGAIN;
/*
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Please Try Again"
message:nil
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles: nil];
[alert show];
*/
} else if (result.isCancelled)
{
STOP_LOAD;
NSLog(#"Cancelled");
} else
{
NSLog(#"Logged in");
NSLog(#"Result=%#",result);
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:#{ #"fields": #"id,first_name,middle_name,last_name,name,picture,email"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error)
{
NSLog(#"Facebook result=%#",result);
if (!error)
{
[NSUSER setObject:result forKey:#"user_info"];
[NSUSER setObject:[result objectForKey:#"name"] forKey:#"skip_name"];
[NSUSER synchronize];
API_CALL_ALLOC(ls_apicall);
[ls_apicall Login: STRING([result objectForKey:#"id"])];
} else {
STOP_LOAD;
NSLog(#"An error occurred getting friends: %#", [error localizedDescription]);
}
}];
}
}];
}
else
{
TOAST(TOAST_NETWORK_ERROR);
}
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.
How to get user name, user image, user email when login: didCompleteWithResult: err: method is called in Facebook SDK for iOS version 4.4.
I want to set these values to properties.
- (void)loginButton:(FBSDKLoginButton *)loginButton didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result error:(NSError *)error {
if (error) {
} else if (result.isCancelled) {
} else {
//I want get user info here and set values to properties.
self.userName =
self.userImage =
self.userEmail =
}
}
If you know other solutions, please tell me about it.
Try this
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions:#[#"email",#"user_photos"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if ([result.grantedPermissions containsObject:#"email"]) {
[self fetchData]
}
}];
and in fetchData method
- (void)fetchData {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:nil]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
DLog(#"fetched user:%#", result);
self.userFirstName = [result objectForKey:#"first_name"];
self.userLastName = [result objectForKey:#"last_name"];
self.userEmail = [result objectForKey:#"email"];
NSString *facebookId = [result objectForKey:#"id"];
self.userProfileImage = [NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large", facebookId];
DLog(#"URL=%#",self.userProfileImage);
}
}];
}
How to get username from facebook sdk 4.0 in iOS?
-(IBAction)LoginWithFacebook:(id)sender {
if ([FBSDKAccessToken currentAccessToken]) {
[self getDetailsAndLogin];
}
else{
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions:#[#"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
// Process error
NSLog(#"%#",error.description);
} else if (result.isCancelled) {
// Handle cancellations
NSLog(#"Result Cancelled!");
} else {
// If you ask for multiple permissions at once, you
// should check if specific permissions missing
if ([result.grantedPermissions containsObject:#"email"]) {
// Do work
[self getDetailsAndLogin];
}
}
}];
}
}
-(void)getDetailsAndLogin{
if (LOGGING) {
return;
}
LOGGING = YES;
[super startLoader];
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:nil]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSString *userID = [[FBSDKAccessToken currentAccessToken] userID];
NSString *userName = [result valueForKey:#"name"];
NSString *email = [result valueForKey:#"email"];
NSString *userImageURL = [NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large", [[FBSDKAccessToken currentAccessToken] userID]];
[User LoginWithFbId:userID Username:userName Email:email ImageUrl:userImageURL success:^(User *response) {
[super stopLoader];
UIStoryboard* sb = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
TabViewController *TabVC = [sb instantiateViewControllerWithIdentifier:#"TabViewController"];
[self.navigationController pushViewController:TabVC animated:YES];
} failure:^(NSString *error) {
LOGGING = NO;
[super stopLoader];
[super showAlertWithTitle:#"Cannot Login" Message:error];
}];
}
else{
LOGGING = NO;
[super stopLoader];
NSLog(#"%#",error.localizedDescription);
}
}];
}
here LoginWithFacebook is a button action to get data . Do not forget to import SDK of FBSession which you can get easily from here . Register your app create a key and import this key in your application.
Happy coding
You canĀ“t get the username anymore:
/me/username is no longer available.
Source: https://developers.facebook.com/docs/apps/changelog#v2_0_graph_api
If you want to detect returning users, use the (App Scoped) ID instead.
Easiest Answer would be to check the following after user is logged in:
if ([FBSDKProfile currentProfile])
{
NSLog(#"User name: %#",[FBSDKProfile currentProfile].name);
NSLog(#"User ID: %#",[FBSDKProfile currentProfile].userID);
}
*Use my code its works excellent.
- (IBAction)tapon_facebookLogin:(id)sender {
if ([FBSDKAccessToken currentAccessToken]) {
// TODO:Token is already available.
NSLog(#"FBSDKAccessToken alreay exist");
[self fetchFbUserInfo];
}else{
NSLog(#"FBSDKAccessToken not exist");
FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
[loginManager logInWithReadPermissions:#[#"email",#"public_profile"]
fromViewController:self
handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
//TODO: process error or result
if (!error) {
NSLog(#"result %#",result.debugDescription);
[self fetchFbUserInfo];
}else{
NSLog(#"errorfacebook %#",error.description);
}
}];
}}
-(void)fetchFbUserInfo{
if ([FBSDKAccessToken currentAccessToken])
{
NSLog(#"Token is available : %#",[[FBSDKAccessToken currentAccessToken]tokenString]);
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:#{#"fields": #"id, name, link, first_name, last_name, picture.type(large), email, birthday ,location ,friends ,hometown , friendlists"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error)
{
NSLog(#"resultisfetchFbUserInfo:%#",result);
}
else
{
NSLog(#"ErrorfetchFbUserInfo %#",error);
}
}];}}
I am quite new to objective-C and iPhone Development environment.
I am implementing Facebook login in my app to get User's name, Email and profile Picture. I have successfully implemented login Part and have received name and User ID of the person.
Now i want to get User's Email and Profile Picture from Facebook.But i am not having any Idea how to get it.I am using Facebook IOS SDK v4.0.
How can i fetch User's Profile picture and Email Id from Facebook when i am having User ID?
To get user Email ID you must ask permission for email while logging.
FBSDKLoginButton *loginView = [[FBSDKLoginButton alloc] init];
loginView.readPermissions = #[#"email"];
loginView.frame = CGRectMake(100, 150, 100, 40);
[self.view addSubview:loginView];
You can get user email Id in New SDK using GraphPath.
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:nil]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"fetched user:%# and Email : %#", result,result[#"email"]);
}
}];
}
result would get you all the user Details and result[#"email"] would get you the email for logged in user.
To get Profile picture you can use
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=normal",result[#"id"]]];
NSData *data = [NSData dataWithContentsOfURL:url];
_imageView.image = [UIImage imageWithData:data];
or u can also use FBSDKProfilePictureView to get profile Picture by passing user profile Id:
FBSDKProfilePictureView *profilePictureview = [[FBSDKProfilePictureView alloc]initWithFrame:_imageView.frame];
[profilePictureview setProfileID:result[#"id"]];
[self.view addSubview:profilePictureview];
Refer to :https://developers.facebook.com/docs/facebook-login/ios/v2.3#profile_picture_view
or u can also get both by passing as parameters
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me"
parameters:#{#"fields": #"picture, email"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSString *pictureURL = [NSString stringWithFormat:#"%#",[result objectForKey:#"picture"]];
NSLog(#"email is %#", [result objectForKey:#"email"]);
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:pictureURL]];
_imageView.image = [UIImage imageWithData:data];
}
else{
NSLog(#"%#", [error localizedDescription]);
}
}];
Sorry for this messy answer, this is my first answer ever. You can use FBSDK Graph request to fetch user's all profile infos and FBSDKProfilePictureView class to fetch user's Profile Picture easily.This code is for manually Facebook login UI.
Firstly, you must put this code where login process start:
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions:#[#"public_profile", #"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error)
{
// There is an error here.
}
else
{
if(result.token) // This means if There is current access token.
{
// Token created successfully and you are ready to get profile info
[self getFacebookProfileInfo];
}
}
}];
And If login is successfull, implement this method to get user's public profile;
-(void)getFacebookProfileInfos {
FBSDKGraphRequest *requestMe = [[FBSDKGraphRequest alloc]initWithGraphPath:#"me" parameters:nil];
FBSDKGraphRequestConnection *connection = [[FBSDKGraphRequestConnection alloc] init];
[connection addRequest:requestMe completionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if(result)
{
if ([result objectForKey:#"email"]) {
NSLog(#"Email: %#",[result objectForKey:#"email"]);
}
if ([result objectForKey:#"first_name"]) {
NSLog(#"First Name : %#",[result objectForKey:#"first_name"]);
}
if ([result objectForKey:#"id"]) {
NSLog(#"User id : %#",[result objectForKey:#"id"]);
}
}
}];
[connection start];
Get current logged in user's profile picture:
FBSDKProfilePictureView *pictureView=[[FBSDKProfilePictureView alloc]init];
[pictureView setProfileID:#"user_id"];
[pictureView setPictureMode:FBSDKProfilePictureModeSquare];
[self.view addSubview:pictureView];
You must add refreshing code to your viewDidLoad method:
[FBSDKProfile enableUpdatesOnAccessTokenChange:YES];
Hope This could Help You ..
- (IBAction)Loginwithfacebookaction:(id)sender
{
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logOut];
[login logInWithReadPermissions:#[#"public_profile"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error)
{
NSLog(#"Process error");
}
else if (result.isCancelled)
{
NSLog(#"Cancelled");
}
else
{
[self getFacebookProfileInfos];
}
}];
}
- (void)finishedWithAuth: (GTMOAuth2Authentication *)auth
error: (NSError *) error {
NSLog(#"Received error %# and auth object %#",error, auth);
if (!error)
{
email =signIn.userEmail;
[[NSUserDefaults standardUserDefaults] setObject:email forKey:#"useremail"];
NSLog(#"Received error and auth object %#",signIn.userEmail);
NSLog(#"Received error and auth object %#",signIn.userID);
if ( auth.userEmail)
{
[[[GPPSignIn sharedInstance] plusService] executeQuery:[GTLQueryPlus queryForPeopleGetWithUserId:#"me"] completionHandler:^(GTLServiceTicket *ticket, GTLPlusPerson *person, NSError *error)
{
// this is for fetch profile image
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#",person.image.url]];
NSLog(#"%#",url);
name= person.displayName;
[[NSUserDefaults standardUserDefaults] setObject:name forKey:#"userNameLogin"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"Name:%#",person.displayName);
[self callWebserviceToUploadImage];
}];
}
}
}
-(void)getFacebookProfileInfos {
FBSDKGraphRequest *requestMe = [[FBSDKGraphRequest alloc]initWithGraphPath:#"/me?fields=first_name, last_name, picture, email" parameters:nil];
FBSDKGraphRequestConnection *connection = [[FBSDKGraphRequestConnection alloc] init];
[connection addRequest:requestMe completionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if(result)
{
if ([result objectForKey:#"email"]) {
email = [result objectForKey:#"email"];
[[NSUserDefaults standardUserDefaults] setObject:email forKey:#"useremail"];
}
if ([result objectForKey:#"first_name"]) {
NSLog(#"First Name : %#",[result objectForKey:#"first_name"]);
name = [result objectForKey:#"first_name"];
[[NSUserDefaults standardUserDefaults] setObject:name forKey:#"userNameLogin"];
}
if ([result objectForKey:#"id"])
{
NSLog(#"User id : %#",[result objectForKey:#"id"]);
}
}
[self callfbloginwebservice];
}];
[connection start];
}
#import <FBSDKCoreKit/FBSDKAccessToken.h>
#import <FBSDKCoreKit/FBSDKGraphRequest.h>
Add YourViewController.h
- (IBAction)loginAction:(id)sender {
// https://developers.facebook.com/docs/graph-api/reference/user
// https://developers.facebook.com/docs/ios/graph
if ([FBSDKAccessToken currentAccessToken]) {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:#{#"fields": #"email,name,first_name,last_name"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"fetched user:%#", result);
// Here u can update u r UI like email name TextField
}
}];
}
}