How can we post something on facebook in ios 6 like twitter? - facebook

I am implementing facebook posting in my app. And add some code to post something on facebook account.
My code is as follows.
- (void)publishStory
{
NSLog(#"publish story called .......");
[FBRequestConnection
startWithGraphPath:#"me/feed"
parameters:self.postParams
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
NSString *alertText;
if (error) {
alertText = [NSString stringWithFormat:
#"error: domain = %#, code = %d",
error.domain, error.code];
} else {
alertText = [NSString stringWithFormat:
#"Posted action, id: %#",
[result objectForKey:#"id"]];
}
// Show the result in an alert
[[[UIAlertView alloc] initWithTitle:#"Result"
message:alertText
delegate:self
cancelButtonTitle:#"OK!"
otherButtonTitles:nil]
show];
}];
}
-(IBAction)cancelButtonAction
{
[[self presentingViewController] dismissViewControllerAnimated:YES completion:nil];
}
-(IBAction)shareButtonAction
{
// Add user message parameter if user filled it in
if (![self.postMessageTextView.text isEqualToString:#""]) {
[self.postParams setObject:self.postMessageTextView.text
forKey:#"message"];
}
// Ask for publish_actions permissions in context
if ([FBSession.activeSession.permissions
indexOfObject:#"publish_actions"] == NSNotFound) {
// No permissions found in session, ask for it
[FBSession.activeSession reauthorizeWithPublishPermissions:
[NSArray arrayWithObjects:#"publish_actions",#"publish_stream", nil]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
// If permissions granted, publish the story
NSLog(#"not error");
[self publishStory];
}
}];
} else {
// If permissions present, publish the story
NSLog(#"In else condition");
[self publishStory];
}
}
this is too much code for , "as ios 6 contains integrated facebook in settings."
But I want to post like twitter integration in ios.How can we do that

There are two ways for posting.
1)Post using FBNativeDialog. (inlcude FacebookSDK.framework)
2)Post via SLComposeViewController.
Which one you want to use is up to you.You need to add three frameworks named AdSupport.framework,Accounts.framework and Social.framework.
For using first one you have to include #import "FacebookSDK/FacebookSDK.h" and code for posting is as follows:
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"" message:#"" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
BOOL displayedNativeDialog = [FBNativeDialogs presentShareDialogModallyFrom:self initialText:#"" image:[UIImage imageNamed:#"iossdk_logo.png"] url:[NSURL URLWithString:#"https://developers.facebook.com/ios"]
handler:^(FBNativeDialogResult result, NSError *error)
{
if (error) {
alert.message=#"Fail posting due to some error!";
[alert show];
/* handle failure */
} else {
if (result == FBNativeDialogResultSucceeded) {
alert.message=#"Posted Successfully!";
[alert show];
/* handle success */
} else {
/* handle user cancel */
}
}}];
if (!displayedNativeDialog) {
/* handle fallback to native dialog */
}
For second one you need #import "Social/Social.h" and the code is as follows:
SLComposeViewController *fbComposer =
[SLComposeViewController
composeViewControllerForServiceType:SLServiceTypeFacebook];
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook])
{
SLComposeViewControllerCompletionHandler __block completionHandler=
^(SLComposeViewControllerResult result){
[fbComposer dismissViewControllerAnimated:YES completion:nil];
switch(result){
case SLComposeViewControllerResultCancelled:
default:
{
NSLog(#"Cancelled.....");
}
break;
case SLComposeViewControllerResultDone:
{
NSLog(#"Posted....");
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Sent"
message:nil
delegate:nil
cancelButtonTitle:#"Dismiss"
otherButtonTitles: nil];
[alert show];
}
break;
}};
[fbComposer addImage:[UIImage imageNamed:#"iossdk_logo.png"]];
[fbComposer setInitialText:#"The initial text you want to send"];
[fbComposer addURL:[NSURL URLWithString:#"https://developers.facebook.com/ios"]];
[fbComposer setCompletionHandler:completionHandler];
[self presentViewController:fbComposer animated:YES completion:nil];
}

Related

Tweet, without using the tweet sheet

I'm using below code to share the content (from UITextView, UIImageView) through twitter
-(void)shareViaTweet:(NSString *)shareMessage{
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
{
SLComposeViewController *tweetSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
[tweetSheet setInitialText:[NSString stringWithFormat:#"%#",shareMessage]];
if (self.imageString)
{
[tweetSheet addImage:[UIImage imageNamed:self.imageString]];
}
if (self.urlString)
{
[tweetSheet addURL:[NSURL URLWithString:self.urlString]];
}
[self presentViewController:tweetSheet animated:YES completion:nil];
}
else
{
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Sorry"
message:#"You can't send a tweet right now, make sure your device has an internet connection and you have at least one Twitter account setup"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
But I need share this, without using the pop up view (I think tweet sheet). It's happening because the below code,
[self presentViewController:tweetSheet animated:YES completion:nil];
When I click the button "Share" of my app, I need to post that in twitter.
Edited:
- (IBAction)doneButtonClicked:(id)sender
{
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
NSString *message = messageTextView.text;
//hear before posting u can allow user to select the account
NSArray *arrayOfAccons = [account accountsWithAccountType:accountType];
for(ACAccount *acc in arrayOfAccons)
{
NSLog(#"%#",acc.username); //in this u can get all accounts user names provide some UI for user to select,such as UITableview
}
NSURL *url = [NSURL URLWithString:#"https://api.twitter.com"
#"/1.1/statuses/user_timeline.json"];
NSDictionary *params = #{#"screen_name" : message,
#"forKey":#"status",
#"trim_user" : #"1",
#"count" : #"1"};
// Request access from the user to access their Twitter account
[account requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error)
{
if (granted == YES)
{
// Populate array with all available Twitter accounts
NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];
if ([arrayOfAccounts count] > 0)
{
//use the first account available
ACAccount *acct = [arrayOfAccounts objectAtIndex:0]; //hear this line replace with selected account. than post it :)
SLRequest *request =
[SLRequest requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodPOST
URL:url
parameters:params];
//Post the request
[request setAccount:acct];
//manage the response
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
if(error)
{
//if there is an error while posting the tweet
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Twitter" message:#"Error in posting" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
else
{
// on successful posting the tweet
NSLog(#"Twitter response, HTTP response: %i", [urlResponse statusCode]);
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Twitter" message:#"Successfully posted" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}];
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Twitter" message:#"You have no twitter account" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
else
{
//suppose user not set any of the accounts
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Twitter" message:#"Permission not granted" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
} ];
//[widgetsHandler closeWidget:nil];
//[self postImage:shareImageView.image withStatus:messageTextView.text];
}
Update: Error
To send images u need do something like this
[account requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error)
{
if (granted == YES)
{
// Populate array with all available Twitter accounts
NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];
if ([arrayOfAccounts count] > 0)
{
//use the first account available
ACAccount *acct = [arrayOfAccounts objectAtIndex:0];
//create this request
SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:[NSURL URLWithString:#"https://api.twitter.com"#"/1.1/statuses/update_with_media.json"] parameters: [NSDictionary dictionaryWithObject:message forKey:#"status"]];
UIImage *imageToPost = [UIImage imageNamed:#"image.jpg"];
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0f);//set the compression quality
[postRequest addMultipartData:imageData withName:#"media" type:#"image/jpeg" filename:#"image.jpg"];
//set account and same as above code
....
....
if u wanna share the tweet without using the tweet sheet see my answer it will post on twitter wall without using the tweet sheet see hear and also set the twitter account in the device. hope this helps
unfortunately the class TWRequest is deprecated in iOS 6 but alternatively we can use SLRequest present in the Social framework
the answer for this is similar to the old answer
i commented out something that i dont want but if u want to select which account to use then uncomment the commented code
- (IBAction)doneButtonClicked:(id)sender
{
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
NSString *message = _textView.text;
// NSArray *arrayOfAccons = [account accountsWithAccountType:accountType];
// for(ACAccount *acc in arrayOfAccons)
// {
// NSLog(#"%#",acc.username);
// NSDictionary *properties = [acc dictionaryWithValuesForKeys:[NSArray arrayWithObject:#"properties"]];
// NSDictionary *details = [properties objectForKey:#"properties"];
// NSLog(#"user name = %#",[details objectForKey:#"fullName"]);
// NSLog(#"user_id = %#",[details objectForKey:#"user_id"]);
// }
// Request access from the user to access their Twitter account
[account requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error)
{
if (granted == YES)
{
// Populate array with all available Twitter accounts
NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];
if ([arrayOfAccounts count] > 0)
{
//use the first account available
ACAccount *acct = [arrayOfAccounts objectAtIndex:0];
// Build a twitter request
// TWRequest *postRequest = [[TWRequest alloc] initWithURL:
// [NSURL URLWithString:#"http://api.twitter.com/1/statuses/update.json"] parameters:[NSDictionary dictionaryWithObject:message forKey:#"status"] requestMethod:TWRequestMethodPOST]; //commented the deprecated method of TWRequest class
SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:[NSURL URLWithString:#"http://api.twitter.com/1/statuses/update.json"] parameters:[NSDictionary dictionaryWithObject:message forKey:#"status"]]; //use this method instead
//Post the request
[postRequest setAccount:acct];//set account
//manage the response
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
if(error)
{
//if there is an error while posting the tweet
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Twitter" message:#"Error in posting" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
// on successful posting the tweet
NSLog(#"Twitter response, HTTP response: %i", [urlResponse statusCode]);
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Twitter" message:#"Successfully posted" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
}];
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Twitter" message:#"You have no twitter account" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
else
{
//suppose user not set any of the accounts
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Twitter" message:#"You have no twitter account" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
} ];
[account release];
}

Facebook SDK 3.5 is not working on ios 5.1

I have implemented facebook in my application. It is working on ios 6 but when it os run on ios5 it is giving error as " The operation coudn't be completed (com.facebook.sdk error 2)"
Following is my code
- (void)postStatusUpdateClick:(NSString *)url:(UIViewController*)view:(UIView*)view1
{
NSString *shareString=[NSString stringWithFormat:#"Check out this great deal at %#",url];
NSURL *urlToShare = [NSURL URLWithString:url];
FBAppCall *appCall = [FBDialogs presentShareDialogWithLink:urlToShare
name:#"Hello Facebook"
caption:nil
description:shareString
picture:nil
clientState:nil
handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
if (error) {
NSLog(#"Error: %#", error.description);
} else {
NSLog(#"Success!");
}
}];
if (!appCall) {
// Next try to post using Facebook's iOS6 integration
BOOL displayedNativeDialog = [FBDialogs presentOSIntegratedShareDialogModallyFrom:view
initialText:shareString
image:nil
url:urlToShare
handler:^(FBOSIntegratedShareDialogResult result, NSError *error) {
if (error && [error code] == 7) {
return;
} NSString *alertText = #"";
if (error) {
alertText = [NSString stringWithFormat:
#"error: domain = %#, code = %d",
error.domain, error.code];
} else if (result == FBNativeDialogResultSucceeded) {
alertText = #"Posted successfully.";
}
if (![alertText isEqualToString:#""]) {
// Show the result in an alert
[[[UIAlertView alloc] initWithTitle:#"Result"
message:alertText
delegate:self
cancelButtonTitle:#"OK!"
otherButtonTitles:nil]
show];
}
}];
if (!displayedNativeDialog) {
// Lastly, fall back on a request for permissions and a direct post using the Graph API
[self performPublishAction:^{
[FBRequestConnection startForPostStatusUpdate:shareString
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
[self showAlert:#"jhj" result:result error:error];
}];
}];
}
}
}
- (void)showAlert:(NSString *)message
result:(id)result
error:(NSError *)error {
NSString *alertMsg;
NSString *alertTitle;
if (error) {
alertTitle = #"Error";
if (error.fberrorShouldNotifyUser ||
error.fberrorCategory == FBErrorCategoryPermissions ||
error.fberrorCategory == FBErrorCategoryAuthenticationReopenSession) {
alertMsg = error.fberrorUserMessage;
} else {
alertMsg = #"Operation failed due to a connection problem, retry later.";
}
} else {
NSDictionary *resultDict = (NSDictionary *)result;
alertMsg = [NSString stringWithFormat:#"Successfully posted '%#'.", message];
NSString *postId = [resultDict valueForKey:#"id"];
if (!postId) {
postId = [resultDict valueForKey:#"postId"];
}
if (postId) {
alertMsg = [NSString stringWithFormat:#"%#\nPost ID: %#", alertMsg, postId];
}
alertTitle = #"Success";
}
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle
message:alertMsg
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
- (void) performPublishAction:(void (^)(void)) action {
if ([[FBSession activeSession]isOpen]) {
/*
* if the current session has no publish permission we need to reauthorize
*/
if ([[[FBSession activeSession]permissions]indexOfObject:#"publish_actions"] == NSNotFound) {
[[FBSession activeSession] requestNewPublishPermissions:[NSArray arrayWithObject:#"publish_action"] defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session,NSError *error){
if (!error) {
action();
}
}];
}else{
//[self publishStory];
action();
}
}else{
/*
* open a new session with publish permission
*/
[FBSession openActiveSessionWithPublishPermissions:[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
// if login fails for any reason, we alert
if (error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
When I Debugged the code it is showing FBSessionStateClosedLoginFailed

Fetching user details from Facebook in iOS

I'm new to iPhone development. I'm doing an App where the user has 2 login through Facebook, once he submits his credentials and clicks on Sign In button, I have to fetch details like First name, email and gender from Facebook and after fetching the user has to be directed to the Registration page of the app with the details filled and i need this app to be compatible for iPhone 4,4s and 5.
I tried doing this using the Facebook Graph API but couldn't get it, so anyone can help me out.
Thanks in Advance.
You can do this by using following code :
[FBSession openActiveSessionWithReadPermissions:#[#"email",#"user_location",#"user_birthday",#"user_hometown"]
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
switch (state) {
case FBSessionStateOpen:
[[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);
NSLog(#"FB user location:%#",user.location);
NSLog(#"FB user username:%#",user.username);
NSLog(#"FB user gender:%#",[user objectForKey:#"gender"]);
NSLog(#"email id:%#",[user objectForKey:#"email"]);
NSLog(#"location:%#", [NSString stringWithFormat:#"Location: %#\n\n",
user.location[#"name"]]);
}
}];
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
break;
}
} ];
and don't forgot to import FacebookSDK/FacebookSDK.h in your code.
EDIT : Update for Facebook SDK v4 (23 April,2015)
Now, Faceboook have released new SDK with major changes. In which FBSession class is deprecated. So all users are suggested to migrate to new sdk and APIs.
Below I have mentioned, how we can get user details via Facebook SDK v4 :
if ([FBSDKAccessToken currentAccessToken]) {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:nil]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#”fetched user:%#”, result);
}
}];
}
But before fetching user details, we have to integrate new Facebook login in our code as described in Documentation here.
Here is the Changelog for SDK v4. I suggest going through it for being updated.
Add info.plist file:
- (IBAction)btn_fb:(id)sender
{
if (!FBSession.activeSession.isOpen)
{
NSArray *_fbPermissions = #[#"email",#"publish_actions",#"public_profile",#"user_hometown",#"user_birthday",#"user_about_me",#"user_friends",#"user_photos",];
[FBSession openActiveSessionWithReadPermissions:_fbPermissions allowLoginUI:YES completionHandler:^(FBSession *session,FBSessionState state, NSError *error)
{
if (error)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else if(session.isOpen)
{
[self btn_fb:sender];
}
}];
return;
}
[FBRequestConnection startWithGraphPath:#"me" parameters:[NSDictionary dictionaryWithObject:#"cover,picture.type(large),id,name,first_name,last_name,gender,birthday,email,location,hometown,bio,photos" forKey:#"fields"] HTTPMethod:#"GET" completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
{
if (!error)
{
if ([result isKindOfClass:[NSDictionary class]])
{
NSLog(#"%#",result);
}
}
}
}];
}
Please refer these following links, sothat you can get some idea.
https://www.parse.com/tutorials/integrating-facebook-in-ios
Facebook iOS 6 - get user info
get Facebook user profile data after getting access token in iOS 5
Display a user's profile name and image through the Facebook instance for iOS
How to cache Facebook User Info with Facebook Login in IOS App
How do I get the full User object using Facebook Graph API and facebook ios sdk?
Hope it will helps you....
Use the FBConnect API for fetch user information.its easy to use
Fbconnect API
Hope it Works For you :)
you have to use graph path to get user Information.
-(void)getEmailId
{
[facebook requestWithGraphPath:#"me" andDelegate:self];
}
- (void)openSession
{
if (internetActive) {
NSArray *permissions=[NSArray arrayWithObjects:#"read_stream",#"email",nil];
[FBSession openActiveSessionWithReadPermissions:permissions allowLoginUI:YES completionHandler:
^(FBSession *session,
FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
}];
}else
{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"" message:#"Internet Not Connected" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
}
#pragma mark- request delegate methods
- (void)request:(FBRequest *)request didLoad:(id)result
{
NSLog(#"request did load successfully....");
// __block NSDictionary *dictionary=[[NSDictionary alloc] init];
if ([result isKindOfClass:[NSDictionary class]]) {
NSDictionary* json = result;
NSLog(#"email id is %#",[json valueForKey:#"email"]);
NSLog(#"json is %#",json);
[[NSUserDefaults standardUserDefaults] setValue:[json valueForKey:#"email"] forKey:#"fbemail"];
[self.viewController login:YES];
}
}
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error
{
UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:#"" message:#"Server not responding.." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertView show];
[self fblogout];
[self showLoginView];
NSLog(#"request did fail with error");
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen: {
//state open action
}
// Initiate a Facebook instance
facebook = [[Facebook alloc]
initWithAppId:FBSession.activeSession.appID
andDelegate:nil];
// Store the Facebook session information
facebook.accessToken = FBSession.activeSession.accessToken;
facebook.expirationDate = FBSession.activeSession.expirationDate;
if (![[NSUserDefaults standardUserDefaults] valueForKey:#"fbemail"]) {
[MBProgressHUD showHUDAddedTo:self.viewController.view animated:YES];
[self getEmailId];
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
// Once the user has logged in, we want them to
// be looking at the root view.
[self.navController popToRootViewControllerAnimated:NO];
[FBSession.activeSession closeAndClearTokenInformation];
facebook = nil;
[self showLoginView];
break;
default:
break;
}
[[NSNotificationCenter defaultCenter]
postNotificationName:FBSessionStateChangedNotification
object:session];
if (error) {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
FBRequest *request = [FBRequest requestForMe];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
// handle successful response
} else if ([error.userInfo[FBErrorParsedJSONResponseKey][#"body"][#"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");
[self logoutButtonTouchHandler:nil];
} else {
NSLog(#"Some other error: %#", error);
}
}];
Facebook has currently updated their SDK version to 4.x. To Fetch user's profile information you will need to explicitly call graph API after login success (ask for required permissions).
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"/me"
parameters:#{ #"fields": #"id,name,email"}
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
// Insert your code here
}];

How to get the list of friend without opening FBFriendPickerViewController iOS

I am using Facebook sdk 3.2 for iOS,
There are various sample project available for iOS
But my problem is how can i get the list of friends without opening FBFriendPickerViewController.
In fact i want all my friends facebook id and there
Any help will be appreciated.
Thanks in Advance
Try this:
get friend list using
**[FBRequest requestForMyFriends];**
**FBRequest* friendsRequest = [FBRequest requestForMyFriends];**
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,NSDictionary* result,NSError *error) {
NSArray* friends = [result objectForKey:#"data"]; ......
the coding is as follow but main line is
**[FBRequest requestForMyFriends];**
-(void)sessionStateChanged:(FBSession *)session state:(FBSessionState)state error:(NSError *)error {
switch (state) {
case FBSessionStateOpen: {
if (self != nil) {
[[FBRequest requestForMe] startWithCompletionHandler: ^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (error) {
//error
}else{
FBRequest* friendsRequest = [FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,NSDictionary* result,NSError *error) {
NSArray* friends = [result objectForKey:#"data"];
for (int i = 0; i < [arrFacebookFriends count]; i++) {
UserShare *shareObj = [arrFacebookFriends objectAtIndex:i];
[shareObj release];
shareObj = nil;
}
[arrFacebookFriends removeAllObjects];
for (NSDictionary<FBGraphUser>* friend in friends) {
UserShare *shareObj = [[UserShare alloc] init];
shareObj.userName = friend.name;
shareObj.userFullName = friend.username;
shareObj.userId = [friend.id intValue];
NSLog(#"%#",friend.id);
shareObj.userPhotoUrl = [NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?", friend.id];
[arrFacebookFriends addObject:shareObj];
[shareObj release];
}
[self StopSpinner];
[tblFacebookFriends reloadData];
}];
}
}];
}
FBCacheDescriptor *cacheDescriptor = [FBFriendPickerViewController cacheDescriptor];
[cacheDescriptor prefetchAndCacheForSession:session];
}
break;
case FBSessionStateClosed: {
[self StopSpinner];
UIViewController *topViewController = [self.navigationController topViewController];
UIViewController *modalViewController = [topViewController modalViewController];
if (modalViewController != nil) {
[topViewController dismissViewControllerAnimated:YES completion:nil];
}
//[self.navigationController popToRootViewControllerAnimated:NO];
[FBSession.activeSession closeAndClearTokenInformation];
[self performSelector:#selector(showLoginView) withObject:nil afterDelay:0.5f];
}
break;
case FBSessionStateClosedLoginFailed: {
[self StopSpinner];
[self performSelector:#selector(showLoginView) withObject:nil afterDelay:0.5f];
}
break;
default:
break;
}
[[NSNotificationCenter defaultCenter] postNotificationName:SCSessionStateChangedNotificationFL object:session];
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:#"Error: %#", [FacebookFriendsListViewController FBErrorCodeDescription:error.code]] message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
}

Facebook SDK error 3 and error 2

I have this application I am using for posting on facebook and I am currently facing difficulties in posting on some of the iOS 6.0 devices. I am using facebook SDK 3.1 only and trying to publish action. Following is the code I am using in the class to initiate the read permission.
For the access I am using the following code.
// CALLING THIS CODE BLOCK IN ONE BUTTON ACTION.
if (FBSession.activeSession.isOpen)
{
[self pickaChoice];
}
else
{
[FBSession openActiveSessionWithPublishPermissions:[NSArray arrayWithObjects:#"publish_actions", nil]
defaultAudience:FBSessionDefaultAudienceEveryone
allowLoginUI:YES
completionHandler:
^(FBSession *session,
FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
}];
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state)
{
case FBSessionStateOpen:
[FBSession setActiveSession:session];
[self pickaChoice];
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
// Once the user has logged in, we want them to
// ...
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
break;
}
if (error) {
NSString* message = [NSString stringWithFormat:#"You have disallowed application to post on your behalf."];
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Error"
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[FBSession.activeSession closeAndClearTokenInformation];
}
}
-(void)pickaChoice
{
/* Just a class to select message and then retrieve the message in the next function
-(void)didSelectaPhraseToPost:(NSString *)message */
FBPublishViewController *fbPublishViewController = [[FBPublishViewController alloc] initWithNibName:#"FBPublishViewController"
bundle:[NSBundle mainBundle]];
fbPublishViewController.selectionDelegate = self;
[self presentViewController:fbPublishViewController
animated:YES
completion:^(){
//nil
}];
}
-(void)didSelectaPhraseToPost:(NSString *)message
{
// Selecting a message from a class and retrieving here. This is the message to post on the feed.
[self publishMessage:message];
}
- (void) performPublishAction:(void (^)(void)) action
{
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound) {
[FBSession.activeSession reauthorizeWithPublishPermissions:[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
action();
}
//For this example, ignore errors (such as if user cancels).
}];
} else {
action();
}
}
- (void)publishMessage:(NSString *)message
{
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"APP_NAME", #"name",
message, #"message",
APP_LINK, #"link",
#"APP_PICTURE", #"picture",
nil];
[self.spinner startAnimating];
[self performPublishAction:^{
[FBRequestConnection
startWithGraphPath:#"me/feed"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
[self.spinner stopAnimating];
NSString *messageTitle = nil;
NSString *message = nil;
// If the result came back okay with no errors...
if (result && !error)
{
NSLog(#"accessToken : %#",[FBSession activeSession].accessToken );
NSLog(#"result : %#",result);
messageTitle = #"Success";
message = #"App has posted to facebook";
}else{
NSLog(#"error : %#",error);
messageTitle = #"Error v1.1";
//message = error.localizedDescription;
message = #"Unable to process the request. Please check the permissions for the application.";
[FBSession.activeSession closeAndClearTokenInformation];
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:messageTitle
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
//TODO maybe clear connection here if we want to force an new login
}];
}];
}
Now the problem is on some iOS 6.0 devices it is throwing facebook.sdk.error 3 and on some devices it is throwing facebook.sdk.error 2 even when the application is permitted to post. In the current code I have just changed the message to a custom for more user friendly message but if you go on to print the localizedDescription it will show those.
On most of the iOS 6.0 devices the code is working absolutely fine and the message is posted. Let me know if anyone can find out where the problem exactly is. I have spent like days now in this and still not getting where the problem is.
Edit 1
A pattern I observed that when facebook application is installed and user is logged in through it and not logged in through the native settings I am facing these sort of difficulties.
It would be good if you find out your iOS version and use apple's default facebook shar view for iOS 6.0 and on another side for below version you must need to use Graph API.
I used this method its work for me fine in iOS6, may be its help you.
-(void)openFacebookAuthentication
{
NSArray *permission = [NSArray arrayWithObjects:kFBEmailPermission,kFBUserPhotosPermission, nil];
[FBSession setActiveSession: [[FBSession alloc] initWithPermissions:permission] ];
[[FBSession activeSession] openWithBehavior:FBSessionLoginBehaviorForcingWebView completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
switch (status) {
case FBSessionStateOpen:
[self getMyData];
break;
case FBSessionStateClosedLoginFailed: {
NSString *errorCode = [[error userInfo] objectForKey:FBErrorLoginFailedOriginalErrorCode];
NSString *errorReason = [[error userInfo] objectForKey:FBErrorLoginFailedReason];
BOOL userDidCancel = !errorCode && (!errorReason || [errorReason isEqualToString:FBErrorLoginFailedReasonInlineCancelledValue]);
if(error.code == 2 && ![errorReason isEqualToString:#"com.facebook.sdk:UserLoginCancelled"]) {
UIAlertView *errorMessage = [[UIAlertView alloc] initWithTitle:kFBAlertTitle
message:kFBAuthenticationErrorMessage
delegate:nil
cancelButtonTitle:kOk
otherButtonTitles:nil];
[errorMessage performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:YES];
errorMessage = nil;
}
}
break;
// presently extension, log-out and invalidation are being implemented in the Facebook class
default:
break; // so we do nothing in response to those state transitions
}
}];
permission = nil;
}