Facebook importing details ios - ios

This is the first time i am trying to integrate Facebook into my ios app.
I am trying to import first name, last name and some other details from Facebook. I am able to log in to Facebook but i cannot import the details. I think my code is wrong somewhere and i don't know where!
if (appDelegate.session.isOpen) {
[FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection,
id<FBGraphUser> user,
NSError *error2) {
regdet.firstname = user.first_name;
regdet.lastname = user.last_name;
regdet.email = [user objectForKey:#"email"];
regdet.address1 = [user objectForKey:#"locale"];
regdet.city = [user.location objectForKey:#"name"];
NSLog(#"firstname %#",regdet.firstname);
}];
} else {
if (appDelegate.session.state != FBSessionStateCreated) {
// Create a new, logged out session.
appDelegate.session = [[FBSession alloc] init];
}
// if the session isn't open, let's open it now and present the login UX to the user
[appDelegate.session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error1) {
[FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection,
id<FBGraphUser> user,
NSError *error2) {
regdet.firstname = user.first_name;
regdet.lastname = user.last_name;
regdet.email = [user objectForKey:#"email"];
regdet.address1 = [user objectForKey:#"locale"];
regdet.city = [user.location objectForKey:#"name"];
NSLog(#"firstname %#",regdet.firstname);
}];
[self performSegueWithIdentifier: #"Facebooksegue" sender: self];
}];
}

Try this
FBLoginView *loginView=[[FBLoginView alloc]init];
loginView.delegate=self;
loginView.readPermissions = #[#"first_name",
#"last_name",
#"location",
#"id",
#"access_token",
#"email"];
NSArray* permissions = [NSArray arrayWithObjects: #"email", nil];
loginView.readPermissions = #[#"email"];
loginView.readPermissions=permissions;
{
[FBSession openActiveSessionWithReadPermissions:Nil allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
[FBRequestConnection
startForMeWithCompletionHandler:^(FBRequestConnection *connection,
id<FBGraphUser> user1,
NSError *error)
{
if (!error)
{
firstname=user1.first_name;
lastname=user1.last_name;
city=[user1.location objectForKey:#"name"];
email=user1[#"email"];
fbid=user1.id;
[[NSUserDefaults standardUserDefaults]setObject:Loggedin forKey:#"token"];
[[NSUserDefaults standardUserDefaults]synchronize];
}
NSURL *url = [[NSURL alloc]initWithString:[NSString stringWithFormat:#"%#action=currfbuser&email=%#&fb_id=%#",MainURL,email,fbid ]];
NSError *errors;
NSData *data = [NSData dataWithContentsOfURL:url];
NSDictionary *json = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errors];
NSString *status = json[#"status"];
user = json[#"user"];
if ([status isEqualToString:#"success"])
{
[self performSegueWithIdentifier: #"LogIN" sender: self];
}
else if (!([fbid isEqualToString:#""]))
{
[self performSegueWithIdentifier: #"Facebooksegue" sender: self];
}
NSLog(#"%#",firstname);
NSLog(#"%#",lastname);
NSLog(#"%#",city);
NSLog(#"%#",email);
NSLog(#"%#",fbid);
}];}];
}

Here is Facebook documentation and example. You need to ask for additional permission.
[FBSession openActiveSessionWithReadPermissions:#[#"basic_info", #"email"]
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
// Respond to session state changes,
// ex: updating the view
}];
Here is Facebook permission keys and description

Related

How to fetch Facebook user information in ios

I am trying to develop a simple app, which, retrieves data from Facebook, when the user connects to it.
I tried this code for it.
NSArray *permissions = [[NSArray alloc] initWithObjects:#"user_birthday",#"user_hometown",#"user_location",#"email",#"basic_info", nil];
[FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
}];
[FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
NSLog(#"%#", [result objectForKey:#"gender"]);
NSLog(#"%#", [result objectForKey:#"hometown"]);
NSLog(#"%#", [result objectForKey:#"birthday"]);
NSLog(#"%#", [result objectForKey:#"email"]);
}];
But when I run this code, it gives an error "FBSDKLog: Error for request to endpoint 'me': An open FBSession must be specified for calls to this endpoint."
Thanks in advance, really appreciate your help.
The error is very appropriate, what it is trying to say is that request connection method should be called once the session is open.
Now your
[FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
}];
method returns BOOL value true or false to specify you wether session is open or not(it tries to open synchronously). So first check the result of this call and the put it inside the code for fetching info. For eg.
if (FBSession.activeSession.isOpen)
{
[FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
NSLog(#"%#", [result objectForKey:#"gender"]);
NSLog(#"%#", [result objectForKey:#"hometown"]);
NSLog(#"%#", [result objectForKey:#"birthday"]);
NSLog(#"%#", [result objectForKey:#"email"]);
}];
}
This should remove your error, but you still may not get the results.You may or may not get result on the very first call to this code but whenever the code for completion handler will be called, this method FBRequestConnection will also get called and at that time you'll get the results as it is an asynchronous call.
If it still doesn't work try this
if (FBSession.activeSession.isOpen)
{
[[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (error)
{
NSLog(#"error:%#",error);
}
else
{
// retrive user's details at here as shown below
NSLog(#"FB user first name:%#",user.first_name);
NSLog(#"FB user last name:%#",user.last_name);
NSLog(#"FB user birthday:%#",user.birthday);
}
}];
`(void)fbAccountConfigureWithBlock:(void (^)(id, NSString *))block
{
_block_data=block;
if(![SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook])
{
dispatch_async(dispatch_get_main_queue(), ^{
[self showAlertMessage:#"" message:#"Please go to settings and add at least one facebook account."];
_block_data(nil,nil);
});
return;
}
ACAccountStore *store = [[ACAccountStore alloc]init];
ACAccountType *accountType = [store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
[store requestAccessToAccountsWithType:accountType
options:#{ACFacebookAppIdKey : FacebookAppId,
ACFacebookAudienceKey : ACFacebookAudienceFriends,
ACFacebookPermissionsKey : #[#"email"]}
completion:^(BOOL granted, NSError *error)
{
if(granted){
NSArray *array = [store accountsWithAccountType:accountType];
if(!array.count){
dispatch_sync(dispatch_get_main_queue(), ^{
[self showAlertMessage:#"" message:#"Please go to settings and add at least one facebook account."];
_block_data(nil,nil);
});
}
else{
ACAccount *account = array[0];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:[NSURL URLWithString:#"https://graph.facebook.com/me"]
parameters: #{#"fields":#"id,first_name,last_name,name,email,picture.height(180).width(180)"}];
[request setAccount:account];
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
if(!error){
NSDictionary *userData = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
NSLog(#"Facebook user data ----> %#",userData);
dispatch_async(dispatch_get_main_queue(), ^{
if(userData[#"error"] != nil)
[self attemptRenewCredentials:store account:account];
else
_block_data(userData,nil);
});
}
else{
dispatch_async(dispatch_get_main_queue(), ^{
[self showAlertMessage:#"" message:error.localizedDescription];
_block_data(nil,nil);
});
}
}];
}
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
[self showAlertMessage:#"" message:#"We need permission to access your facebook account in order make registration."];
_block_data(nil,nil);
});
}
}];
}`

Reading information from Facebook

I am a beginner in iOS. I am trying to create an app and referred a lot of posts in the stackoverflow and some other sites and i used the following code to access the Facebook account.
AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
if (appDelegate.session.isOpen) {
[appDelegate.session closeAndClearTokenInformation];
} else {
if (appDelegate.session.state != FBSessionStateCreated) {
appDelegate.session = [[FBSession alloc] init];
}
[appDelegate.session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
}];
}
After that in a function i used the following code to access the Facebook details of the user.
if (FBSession.activeSession.isOpen) {
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *user,
NSError *error) {
if (!error) {
_FirstName.text = user.first_name;
regisrationdetails.fbid = user.id;
_LastName.text=user.last_name;
_EmailAddress.text=user.email;
NSArray *locationarray=[[NSArray alloc]initWithObjects:user.location,nil];
_City.text=[locationarray objectAtIndex:1];
NSLog(#"%#",user.first_name);
}
}];
No error is being shown but i can't get the information from Facebook the the text fields.If anyone good at this knows how to access the information then please help me out.
- (IBAction)getMeButtonTapped:(id)sender {
if(!_accountStore)
_accountStore = [[ACAccountStore alloc] init];
ACAccountType *facebookTypeAccount = [_accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
[_accountStore requestAccessToAccountsWithType:facebookTypeAccount
options:#{ACFacebookAppIdKey: #"571438296262222", ACFacebookPermissionsKey: #[#"email"]}
completion:^(BOOL granted, NSError *error) {
if(granted){
NSArray *accounts = [_accountStore accountsWithAccountType:facebookTypeAccount];
_facebookAccount = [accounts lastObject];
NSLog(#"Success");
[self me];
}else{
// ouch
NSLog(#"Fail");
NSLog(#"Error: %#", [error localizedDescription]);
}
}];
}
- (void)me
{
NSURL *meurl = [NSURL URLWithString:#"https://graph.facebook.com/me"];
SLRequest *merequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:meurl
parameters:nil];
merequest.account = _facebookAccount;
[merequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSString *meDataString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#", meDataString);
}];}
Use this hope this helps you, also add social framework as well as Accounts Framework
try this..
- (void)fetchFacebookUserInfo {
if ( FBSession.activeSession.isOpen) {
[FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection,
id<FBGraphUser> user,
NSError *error) {
if (!error) {
NSString *name = user.name;
NSString *userName = user.username;
NSString *firstName = user.first_name;
NSString *lastName = user.last_name;
NSString *email1 = [user objectForKey:#"email"];
NSString *birthday1 = user.birthday;
NSString *locale = [user objectForKey:#"locale"];
NSString *location = [user.location objectForKey:#"name"];
}
}];
}

Retrieve the friends Email address From Facebook SDK in ios

I am tried to retrieve the Email Address from Facebook Friends.but,It cannot retrieved the email address.
I printed the email address.but,It displays the null.
I added email address in permissions array,FBRequest.
-(void)LoginButtonTapped
{
[FBSession.activeSession openWithCompletionHandler:^(FBSession *session,
FBSessionState state,
NSError *error)
{
if (FBSession.activeSession.isOpen)
{
NSLog(#"TOKEN : %#",[[FBSession activeSession]accessTokenData]);
FBRequest *friendRequest = [FBRequest requestForGraphPath:#"me/friends?fields=name,picture,birthday,email,location"];
[friendRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
NSArray *data = [result objectForKey:#"data"];
for (FBGraphObject<FBGraphUser> *friend in data)
{
[delegate.friendsListArray addObject:friend];
NSLog(#"%#:%#:%#:", [friend name],[friend birthday],[friend id]);
NSString *email=[friend objectForKey:#"email"];
NSLog(#"Email:%#",email);
}
}];
}
}];
}
- (void) performPublishAction:(void (^)(void)) action
{
NSArray *permissions = [[NSArray alloc] initWithObjects:#"user_birthday",#"user_location",#"friends_email",#"friends_hometown",#"friends_birthday",#"friends_location",#"publish_actions",#"user_photos",nil];
[[delegate facebook]authorize:permissions];
if ([FBSession.activeSession.permissions indexOfObject:permissions] == NSNotFound)
{
[FBSession.activeSession requestNewPublishPermissions:permissions
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
action();
}
}];
}
else
{
action();
}
[permissions release];
}
Any ideas please help me.
Shot in the dark but did you check your error value? Also what's the count of the # of records you get back?
Also could just try this instead, which seems to work (you might need to use objectForKey to get email out of the object):
FBRequest* friendsRequest = [FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,
NSDictionary* result,
NSError *error) {
NSArray* friends = [result objectForKey:#"data"];
NSLog(#"Found: %i friends", friends.count);
for (NSDictionary<FBGraphUser>* friend in friends) {
NSLog(#"I have a friend named %# with id %#", friend.name, friend.id);
}
}];

How not to ask for publish permission everytime?

I did this in facebook
[self vSuspendAndHaltThisThreadTillUnsuspendedWhileDoing:^{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self.ACAstore requestAccessToAccountsWithType:self.ACAccounts options:[self dicPostOptions] completion:^(BOOL granted, NSError *error) {
self.bPermissionToAccessStoreGranted=granted;
[self vContinue];
}];
}];
}];
Basically I am asking for publish permission. What I want to do is to check whether such publish permission has been granted or not before asking again.
How to do so?
To check permissions available:
if(![postRequest.session.permissions containsObject:#"publish_actions"])
You can make an FBRequest with the open graph API with me/permissions. It will return you a response with a dictionary where the key are the permissions.
FBRequest *req = [FBRequest requestWithGraphPath:#"me/permissions" parameters:Nil HTTPMethod:#"GET"];
[req startWithCompletionHandler: ^(FBRequestConnection *connection,
NSDictionary* result,
NSError *error) {
BOOL canPublish = FALSE;
if (!error)
{
FBGraphObject *data = [result objectForKey:#"data"];
for(NSDictionary<FBGraphObject> *aKey in data)
{
canPublish = [[aKey objectForKey:#"publish_stream"] boolValue];
}
}
else
{
NSLog(#"%#", error);
}
NSLog(#"%#", canPublish ? #"I have publish perms" : #"I don't have publish perms");
}];
Try this -
First of all implement all the facebook sdk delegate methods in your app delegate.
- (IBAction)loginWithFacebookButtonTapped:(id)sender
{
IntubeAppDelegate *delegat = (IntubeAppDelegate*)[[UIApplication sharedApplication] delegate];
[delegat doLoginAndSwitch];
}
Now, in your appDelegate -
-(void) doLoginAndSwitch
{
[self openSessionWithAllowLoginUI:YES];
}
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI
{
NSArray *permissions = [NSArray arrayWithObjects:#"email", nil];
return [FBSession openActiveSessionWithPublishPermissions:permissions
defaultAudience:FBSessionDefaultAudienceFriends
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
[self sessionStateChanged:session
state:state
error:error];
}];
}
-(BOOL)openSessionWithAllowPublishStreamPermission:(BOOL)allowLoginUI
{
NSArray *permissions = [NSArray arrayWithObjects:#"publish_actions",#"publish_stream", nil];
[[FBSession activeSession] requestNewPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceEveryone completionHandler:^(FBSession *session, NSError *error){
}];
return YES;
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState)state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen:
if(!error)
{
// NSLog(#"FBSessionStateOpen :- logged in");
[self openSessionWithAllowPublishStreamPermission:YES];
// Your code
}
}
}
I hope you would get what you desire now. :)

Facebook SDK and iOS

I am trying to post a status using Facebook SDK.
Some of the users are already signed in using Facebook.
So I have this code:
if (FBSession.activeSession.isOpen) {
NSLog(#"Already Open%#",[[FBSession activeSession] accessTokenData].accessToken);
// NSString *tok = [[FBSession activeSession] accessTokenData].accessToken;
NSArray *permissions = [NSArray arrayWithObjects:#"publish_actions", nil];
[[FBSession activeSession] requestNewPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session,NSError *error) {
if(!error){
NSLog(#"Publish Permission Granted");
}
else
{
NSLog(#"Publish to get Read Permission");
} }];
//Remove indicator
[_activityView removeFromSuperview];
} else {
// OPEN Session!
[FBSession openActiveSessionWithReadPermissions:nil
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
// if login fails for any reason, we alert
if (error) {
// show error to user.
} else if (FB_ISSESSIONOPENWITHSTATE(status)) {
// no error, so we proceed with requesting user details of current facebook session.
NSLog(#"----%#",[session accessTokenData].accessToken);
//NSString *tok = [session accessTokenData].accessToken;
NSArray *permissions = [NSArray arrayWithObjects:#"publish_actions", nil];
[[FBSession activeSession] requestNewPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session,NSError *error) {
if(!error){
NSLog(#"Publish Permission Granted");
}
else
{
NSLog(#"Publish to get Read Permission");
} }];
[_activityView removeFromSuperview];
// [self promptUserWithAccountName]; // a custom method - see below:
}
}];
}
So lets focus on the first part which is suppose that the user has open session( the second one is just opening a new one in case that is no session available). How I am going to post a status with a url and a picture after granting publish permissions? Facebook examples are not helping at all. I found some other examples but most of them are outdated.
I managed to post a simple post with:
FBRequest *postRequest = [FBRequest requestForPostStatusUpdate:#"hi" ];
[postRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
// TODO: Check for success / failure here
}];
after granding publish permission. I want something similar with url description imgurl and title.
This is how I did it, in my ibaction method:
Sharing Image:
UIImage *img = myImage;
FBLoginView *loginview = [[FBLoginView alloc] init];
loginview.delegate = self;
[self performPublishAction:^{
[FBRequestConnection startForUploadPhoto:img
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
[self showAlert:#"Photo Post" result:result error:error];
}];
}];
Sharing URL:
NSURL *urlToShare = [NSURL URLWithString:#"http://developers.facebook.com/ios"];
FBAppCall *appCall = [FBDialogs presentShareDialogWithLink:urlToShare
name:#"Hello Facebook"
caption:nil
description:#"The 'Hello Facebook' sample application showcases simple Facebook integration."
picture:nil
clientState:nil
handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
if (error) {
NSLog(#"Error: %#", error.description);
} else {
NSLog(#"Success!");
}
}];
Add these as well:
- (void) performPublishAction:(void (^)(void)) action
{
if([[FBSession activeSession]isOpen])
{
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound) {
// if we don't already have the permission, then we request it now
[FBSession.activeSession requestNewPublishPermissions:#[#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
action();
}
//For this example, ignore errors (such as if user cancels).
}];
} else {
action();
}
}
else
{
[FBSession openActiveSessionWithPublishPermissions:[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if (!error && status == FBSessionStateOpen) {
}else{
NSLog(#"Session error");
[self fbResync];
[NSThread sleepForTimeInterval:0.5]; //half a second
[FBSession openActiveSessionWithPublishPermissions:[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState status, NSError *error){
}];
}
}];
}
}
- (void)loginViewShowingLoggedInUser:(FBLoginView *)loginView
{
}
- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView
user:(id<FBGraphUser>)user
{
self.loggedInUser = user;
}
- (void)loginViewShowingLoggedOutUser:(FBLoginView *)loginView
{
self.loggedInUser = nil;
}
-(void)fbResync
{
ACAccountStore *accountStore;
ACAccountType *accountTypeFB;
if ((accountStore = [[ACAccountStore alloc] init]) && (accountTypeFB = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook] ) ){
NSArray *fbAccounts = [accountStore accountsWithAccountType:accountTypeFB];
id account;
if (fbAccounts && [fbAccounts count] > 0 && (account = [fbAccounts objectAtIndex:0])){
[accountStore renewCredentialsForAccount:account completion:^(ACAccountCredentialRenewResult renewResult, NSError *error) {
//we don't actually need to inspect renewResult or error.
if (error){
}
}];
}
}
}
Hope this helps... Look at HelloFacebookSample in Facebook SDK Samples.
Try this:
[self performPublishAction:^{
NSString *message = [NSString stringWithFormat:#"Updating status for %# at %#", self.loggedInUser.first_name, [NSDate date]];
[FBRequestConnection startForPostStatusUpdate:message
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
[self showAlert:message result:result error:error];
self.buttonPostStatus.enabled = YES;
}];
self.buttonPostStatus.enabled = NO;
}];

Resources