I am trying to follow the Parse tutorial for Logging in With Facebook. However, the sample code does not match up with the guide, so the code there is useless. I have followed the guide completely, but after I login, it directs me to Facebook app, I give permission, it goes back to the app I am building, but I get the following error
FBSDKLog: Error for request to endpoint 'me': An open FBSession must be specified for calls to this endpoint.
What is going on? In Login controller:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
FBRequest *request = [FBRequest requestForMe];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
// handle successful response
} else if ([[[[error userInfo] objectForKey:#"error"] objectForKey:#"type"]
isEqualToString: #"OAuthException"]) { // Since the request failed, we can check if it was due to an invalid session
NSLog(#"The facebook session was invalidated");
[self logoutButtonAction:nil];
} else {
NSLog(#"Some other error: %#", error);
}
}];
if ([PFUser currentUser] && // Check if user is cached
[PFFacebookUtils isLinkedWithUser:[PFUser currentUser]]) { // Check if user is linked to Facebook
// Present the next view controller without animation
[self _presentUserDetailsViewControllerAnimated:NO];
}
}
- (IBAction)loginButtonTouchHandler:(id)sender {
// Set permissions required from the facebook user account
NSArray *permissionsArray = #[ #"user_about_me", #"user_relationships", #"user_birthday", #"user_location"];
[PFFacebookUtils initializeFacebook];
// Login PFUser using Facebook
[PFFacebookUtils logInWithPermissions:permissionsArray block:^(PFUser *user, NSError *error) {
[_activityIndicator stopAnimating]; // Hide loading indicator
if (!user) {
NSString *errorMessage = nil;
if (!error) {
NSLog(#"Uh oh. The user cancelled the Facebook login.");
errorMessage = #"Uh oh. The user cancelled the Facebook login.";
} else {
NSLog(#"Uh oh. An error occurred: %#", error);
errorMessage = [error localizedDescription];
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Log In Error"
message:errorMessage
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:#"Dismiss", nil];
[alert show];
} else {
if (user.isNew) {
NSLog(#"User with facebook signed up and logged in!");
} else {
NSLog(#"User with facebook logged in!");
}
[self _presentUserDetailsViewControllerAnimated:YES];
}
}];
[_activityIndicator startAnimating]; // Show loading indicator until login is finished
}
- (void)_presentUserDetailsViewControllerAnimated:(BOOL)animated {
UserDetailsViewController *detailsViewController = [[UserDetailsViewController alloc] init];
[self.navigationController pushViewController:detailsViewController animated:YES];
}
In my UserDetailsViewController:
- (void)viewDidLoad {
// ...
[self _loadData];
}
- (void)_loadData {
// ...
FBRequest *request = [FBRequest requestForMe];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
// result is a dictionary with the user's Facebook data
NSDictionary *userData = (NSDictionary *)result;
NSString *facebookID = userData[#"id"];
NSString *name = userData[#"name"];
NSString *location = userData[#"location"][#"name"];
NSString *gender = userData[#"gender"];
NSString *birthday = userData[#"birthday"];
NSString *relationship = userData[#"relationship_status"];
NSURL *pictureURL = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large&return_ssl_resources=1", facebookID]];
// URL should point to https://graph.facebook.com/{facebookId}/picture?type=large&return_ssl_resources=1
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:pictureURL];
// Run network request asynchronously
[NSURLConnection sendAsynchronousRequest:urlRequest
queue:[NSOperationQueue mainQueue]
completionHandler:
^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError == nil && data != nil) {
// Set the image in the header imageView
self.headerImageView.image = [UIImage imageWithData:data];
}
}];
// Now add the data to the UI elements
// ...
}
}];
}
We figured it out, when trying to create an auto-login feature with this function:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
FBRequest *request = [FBRequest requestForMe];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
// handle successful response
} else if ([[[[error userInfo] objectForKey:#"error"] objectForKey:#"type"]
isEqualToString: #"OAuthException"]) { // Since the request failed, we can check if it was due to an invalid session
NSLog(#"The facebook session was invalidated");
[self logoutButtonAction:nil];
} else {
NSLog(#"Some other error: %#", error);
}
}];
if ([PFUser currentUser] && // Check if user is cached
[PFFacebookUtils isLinkedWithUser:[PFUser currentUser]]) { // Check if user is linked to Facebook
// Present the next view controller without animation
[self _presentUserDetailsViewControllerAnimated:NO];
}
}
We actually end up skipping the [PFFacebookUtils initializeFacebook] call, since it only happens when you push the login button. The solution is to put this call in the appDelegate in the method application:didFinishLaunchingWithOptions:
Related
I am trying to login a user through facebook in my parse.com app. I have all the ids and appdelegate methods in place.
I have created a view in the storyboard and made that a facebook login button and then i have connected it to my .h file as a IBAction.
my code:
- (IBAction)fblogin:(FBSDKLoginButton *)sender {
[PFFacebookUtils logInInBackgroundWithReadPermissions:#[#"public_profile", #"email"] block:^(PFUser *user, NSError *error) {
if (error) {
// NSLog(#"Uh oh. The user cancelled the Facebook login.");
UIAlertView *alertVeiw = [[UIAlertView alloc] initWithTitle:#"Sorry" message:[error.userInfo objectForKey:#"error"] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertVeiw show];
} else if (!user) {
UIAlertView *alertVeiw = [[UIAlertView alloc] initWithTitle:#"Sorry" message:#"You cancelled Login, try again!" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertVeiw show];
}else {
// NSLog(#"User logged in through Facebook!");
// [self dismissViewControllerAnimated:YES completion:NULL];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:#{#"fields": #"first_name, last_name, email, public_profile"}];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error)
{
if (error)
{
UIAlertView *alertVeiw = [[UIAlertView alloc] initWithTitle:#"Sorry" message:[error.userInfo objectForKey:#"error"] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertVeiw show];
} else if ([[error userInfo][#"error"][#"type"] isEqualToString: #"OAuthException"]) { // Since the request failed, we can check if it was due to an invalid session
// NSLog(#"The facebook session was invalidated");
[PFFacebookUtils unlinkUserInBackground:[PFUser currentUser]];
}
else {
NSDictionary *userData = (NSDictionary *)result;
// [self requestFacebookUser:user];
NSString *name = userData[#"name"];
NSString *email = userData[#"email"];
user.username = name;
user.email = email;
[user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error)
{
if (error)
{
UIAlertView *alertVeiw = [[UIAlertView alloc] initWithTitle:#"Sorry" message:[error.userInfo objectForKey:#"error"] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertVeiw show];
}
else {
// [self dismissViewControllerAnimated:NO completion:nil];
//[self.navigationController popToRootViewControllerAnimated:NO];
[self performSegueWithIdentifier:#"inbox" sender:self];
}
}];
}
}];
}
}];
}
The faccebook web page opens when i press login facebook button then we sign in and then nothing happens.
Please help me implement facebook login step by step correctly.
EDIT:
app delegate:
[PFFacebookUtils initializeFacebookWithApplicationLaunchOptions: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];
}
applicationWillEnterForeGround:
[FBSDKAppEvents activateApp];
then:
along with your(SanitLee) answer i have these methods:
- (void)loginViewFetchedUserInfo:(FBSDKLoginManager *)loginView
user:(FBSDKProfile*)user {
}
-(void)loginButton:(FBSDKLoginButton *)loginButton didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result error:(NSError *)error{
// [self performSegueWithIdentifier:#"inbox" sender:self];
}
-(void)loginButtonDidLogOut:(FBSDKLoginButton *)loginButton{
}
-(void)loginButtonClicked{
}
i also get this error on whose view is not in the window hierarchy!
Here's how I did it and it works for me.
Firstly, import this in your m file:
#import <ParseFacebookUtils/PFFacebookUtils.h>//fb login for parse
Then the following codes should do what you want:
- (IBAction)loginButtonTouchHandler:(id)sender {
NSArray *permissionsArray = #[ #"user_about_me", #"user_relationships", #"user_birthday", #"user_location"];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
[PFFacebookUtils logInWithPermissions:permissionsArray block:^(PFUser *user, NSError *error) {
if (!user) {
NSString *errorMessage = nil;
if (!error) {
NSLog(#"Uh oh. The user cancelled the Facebook login.");
errorMessage = NSLocalizedString(#"Uh oh. The user cancelled the Facebook login.", nil);
} else {
NSLog(#"Uh oh. An error occurred: %#", error);
errorMessage = [error localizedDescription];
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Log In Error", nil) message:errorMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(#"Dismiss", nil), nil];
[MBProgressHUD hideHUDForView:self.view animated:YES];
[alert show];
} else {
if (user.isNew) {
NSLog(#"User with facebook signed up and logged in!");
[self _loadData];
} else {
NSLog(#"User with facebook logged in!");
}
[MBProgressHUD hideHUDForView:self.view animated:YES];
[self _presentNextViewControllerAnimated:YES];
}
}];
}
- (void)_presentNextViewControllerAnimated:(BOOL)animated {
PAWWallViewController *wallViewController = [[PAWWallViewController alloc] initWithNibName:nil bundle:nil];
[(UINavigationController *)self.presentingViewController pushViewController:wallViewController animated:NO];
[self.presentingViewController dismissModalViewControllerAnimated:YES];
}
- (void)_loadData {
FBRequest *request = [FBRequest requestForMe];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
PFUser *user = [PFUser currentUser];
NSDictionary *userData = (NSDictionary *)result;
NSString *facebookID = userData[#"id"];
NSString *name = userData[#"name"];
NSString *email = userData[#"email"];
NSString *location = userData[#"location"][#"name"];
NSString *gender = userData[#"gender"];
NSString *birthday = userData[#"birthday"];
NSString *relationship = userData[#"relationship_status"];
NSString *facebookLink = [NSString stringWithFormat:#"Facebook.com/%#", facebookID];
NSURL *pictureURL = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large&return_ssl_resources=1", facebookID]];
NSLog(#"facebookID --> %#", facebookID);
NSLog(#"name --> %#", name);
NSLog(#"email --> %#", email);
//for profile image
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:pictureURL];
// Run network request asynchronously
[NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError == nil && data != nil) {
PFFile *userImageFile = [PFFile fileWithName:#"userImage.jpg" data:data];
if (userImageFile) [user setObject:userImageFile forKey:kPAWParseUserImageKey];
}
[user setObject:facebookID forKey:kPAWParseUsernameKey]; //initially use fb id as username to avoid duplication
[user setObject:name forKey:kPAWParseRealnameKey];
[user setObject:facebookLink forKey:kPAWParseFacebookKey];
[user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (!error) {
if (succeeded) {
NSLog(#"fb user saved successfully");
}
} else {
NSLog(#"fb user saved unsuccessfully");
}
}];
}];
} else if ([[[[error userInfo] objectForKey:#"error"] objectForKey:#"type"]
isEqualToString: #"OAuthException"]) {
NSLog(#"The facebook session was invalidated");
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Log out of Spotpost?", nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(#"Log out", nil) otherButtonTitles:NSLocalizedString(#"Cancel", nil), nil];
[alertView show];
} else {
NSLog(#"Some other error: %#", error);
}
}];
}
And here is how I did config in app delegate:
#import <ParseFacebookUtils/PFFacebookUtils.h> //fb login for parse
....
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
...
[PFFacebookUtils initializeFacebook]; //fb login for parse
return YES;
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
....
[FBAppCall handleDidBecomeActiveWithSession:[PFFacebookUtils session]]; //fb login for parse
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
return [FBAppCall handleOpenURL:url
sourceApplication:sourceApplication
withSession:[PFFacebookUtils session]];
}
- (void)applicationWillTerminate:(UIApplication *)application {
[[PFFacebookUtils session] close];
}
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 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
}
}];
}
}
Currently here is my code in my LogInViewController that contains the handler for Facebook signup process and code that I was hoping would setup the username and email address to their Facebook Name and Email address.
- (IBAction)fbButtonPressed:(id)sender
{
NSArray *permissions =#[#"public_profile", #"email", #"user_friends"];
[PFFacebookUtils logInWithPermissions:permissions block:^(PFUser *user, NSError *error) {
if (!user) {
NSLog(#"Uh oh. The user cancelled the Facebook login.");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Log In Error" message:#"Uh oh. The user cancelled the Facebook login." delegate:nil cancelButtonTitle:nil otherButtonTitles:#"Dismiss", nil];
[alert show];
} else if (user.isNew) {
NSLog(#"User signed up and logged in through Facebook!");
FBRequest *request = [FBRequest requestForMe];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error){
NSDictionary *userData = (NSDictionary *)result;
NSString *facebookID= userData[#"ID"];
NSURL *pictureURL = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large&return_ssl_resources=1", facebookID]];
NSMutableDictionary *userProfile = [NSMutableDictionary dictionaryWithCapacity:7];
if (facebookID){
userProfile[#"facebookID"] = facebookID;
}
if (userData[#"name"]) {
user.username = userProfile[#"name"];
}
if (userData[#"email"]){
user.email = userData[#"emai"];
}
[user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error){
NSLog(#"ERROR: %# %#", error, [error userInfo]);
}else{
[self.navigationController popToRootViewControllerAnimated:YES];
}
}];
}
}];
} else {
NSLog(#"User logged in through Facebook!");
[self.navigationController popToRootViewControllerAnimated:YES];
}
}];
}
You have a typo in
user.email = userData[#"emai"];
Also, for the name, you try getting the name from userProfile:
if (userData[#"name"]) {
user.username = userProfile[#"name"];
}
which should be
if (userData[#"name"]) {
user.username = userData[#"name"];
}
Try this.
PFUser *user = [PFUser currentUser];
FBRequest *request = [FBRequest requestForMe];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
NSLog(#"test");
if(!error) {
NSDictionary *userData = (NSDictionary *)result;
NSString *name = userData[#"name"];
user.username = name;
NSLog(#"user:%#", name);
[user saveEventually];
} else {
NSLog(#"An error occurred: %#", error.localizedDescription);
}
}];
I am trying the facebook integration for the first time. I am confused of many codes i am able to get from different tutorial sites.
I have used the following code to fetch user information from facebook data but i am not able to get the data using storyboard. Can someone suggest what is wrong with this code??
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
BOOL wasHandled = [FBAppCall handleOpenURL:url sourceApplication:sourceApplication];
return wasHandled;
}
The following code paragraph under here is not getting excecuted. So is there some other way to get the control into this code??
- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView
user:(id<FBGraphUser>)user {
regisrationdetails.fbid = user.id;
regisrationdetails.firstname = user.first_name;
}
Rest everything i tried different types to call it but its not happening.
- (void)loginView:(FBLoginView *)loginView
handleError:(NSError *)error {
NSString *alertMessage, *alertTitle;
if (error.fberrorShouldNotifyUser) {
alertTitle = #"Facebook Error";
alertMessage = error.fberrorUserMessage;
} else if (error.fberrorCategory == FBErrorCategoryAuthenticationReopenSession) {
alertTitle = #"Session Error";
alertMessage = #"Your current session is no longer valid. Please log in again.";
} else if (error.fberrorCategory == FBErrorCategoryUserCancelled) {
NSLog(#"user cancelled login");
} else {
alertTitle = #"Unknown Error";
alertMessage = #"Error. Please try again later.";
NSLog(#"Unexpected error:%#", error);
}
if (alertMessage) {
[[[UIAlertView alloc] initWithTitle:alertTitle
message:alertMessage
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] show];
}
}
- (void)viewDidLoad
{
[FBLoginView class];
FBLoginView *loginView = [[FBLoginView alloc] init];
loginView.readPermissions= #[#"email", #"user_likes"];
loginView.publishPermissions = #[#"publish_actions"];
loginView.defaultAudience = FBSessionDefaultAudienceFriends;
FBSession *session = [[FBSession alloc] init];
[FBSession setActiveSession:session];
[session openWithBehavior:FBSessionLoginBehaviorWithNoFallbackToWebView
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
}];
[FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
regisrationdetails.firstname = [result objectForKey:#"name"];
}
}];
NSLog(#"%#", regisrationdetails.firstname);
[FBRequestConnection
startForMeWithCompletionHandler:^(FBRequestConnection *connection,
id<FBGraphUser> user,
NSError *error) {
if (!error) {
regisrationdetails.firstname = user.name;
regisrationdetails.address1 = user.location[#"name"];
regisrationdetails.city = user[#"city"];
}
}];
- (IBAction)CreateAccount:(id)sender
{
regisrationdetails.firstname=_FirstName.text;
regisrationdetails.lastname=_LastName.text;
regisrationdetails.email=_EmailAddress.text;
regisrationdetails.address1=_Address1.text;
regisrationdetails.address2=_Address2.text;
regisrationdetails.city=_City.text;
regisrationdetails.state=_State.text;
regisrationdetails.zip=_Zip.text;
NSURL *url = [[NSURL alloc]initWithString:[NSString stringWithFormat:#"%#first_name=%#&last_name=%#&email=%#&address_1=%#&address_2=%#&city=%#&state=%#&zip=%#&&fb_id=%#&action=fbsignin",MainURL, regisrationdetails.firstname,regisrationdetails.lastname,regisrationdetails.email,regisrationdetails.address1,regisrationdetails.address2,regisrationdetails.city,regisrationdetails.state,regisrationdetails.zip,regisrationdetails.fbid ]];
NSError *errors;
NSData *data = [NSData dataWithContentsOfURL:url];
NSDictionary *json = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errors];
status = json[#"status"];
error = json[#"error"];
user = json[#"user"];
if ([status isEqualToString:#"success"])
{
UIAlertView *success=[[UIAlertView alloc]initWithTitle:#"Success" message:nil delegate:self cancelButtonTitle:#"Close" otherButtonTitles:nil];
[success show];
}
else if ([status isEqualToString:#"failure"])
{
messages=[[NSString alloc]init];
for (int i=0; i<[error count]; i++)
{
messages=[messages stringByAppendingString:[error objectAtIndex:i]];
messages=[messages stringByAppendingString:#"\n"];
}
UIAlertView *failure=[[UIAlertView alloc]initWithTitle:#"Failure" message:messages delegate:self cancelButtonTitle:#"Close" otherButtonTitles: nil];
[failure show];
}
}
Is there a simple sample code available to fetch the facebook user information using storyboard??
Make sure you have implement facebook delegate methods,
fbLoginview.delegate = self;
And implement this method to get user information
- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView
user:(id<FBGraphUser>)user {
// here we use helper properties of FBGraphUser to dot-through to first_name and
// id properties of the json response from the server; alternatively we could use
NSLog(#"user :%#",user);
}