I have just made a new app and I have it all set up with Facebook login, and I have been approved for the email permission, but I seem to not to be getting the users email, I think I might be missing something in my code here is what I have:
// Set permissions required from the facebook user account
NSArray *permissionsArray = #[ #"user_about_me", #"user_relationships", #"user_likes", #"user_location", #"email", #"basic_info", #"user_activities", #"user_interests", #"user_birthday"];
// Login PFUser using facebook
[PFFacebookUtils logInWithPermissions:permissionsArray block:^(PFUser *user, NSError *error) {
if (!user) {
if (!error) {
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 {
NSLog(#"Uh oh. An error occurred: %#", error);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Log In Error" message:[error description] delegate:nil cancelButtonTitle:nil otherButtonTitles:#"Dismiss", nil];
[alert show];
}
} else if (user.isNew) {
user[#"school"] = #"";
NSLog(#"User with facebook signed up and logged in!");
}
else {
NSLog(#"User with facebook logged in!");
}
}
}];
If you could show of tell me what I am missing/ why I am not seeing my users email. I would really appreciate it. By the way I am using Parse.com as a backend.
logInWithPermissions: method doesn't save the email attribute by default when it creates a new user. If you want to save the email of a Facebook user, after verifying that the user is already authenticated, you need to call startForMeWithCompletionHandler: method of FBRequestConnection class. Your code should look like this in the last part:
NSLog(#"User with facebook logged in!");
[FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
[[PFUser currentUser] setObject:[result objectForKey:#"email"]
forKey:#"email"];
[[PFUser currentUser] saveInBackground];
}
}];
Related
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];
}
I have integrated facebook sdk 3.2.1 in my app, When i am trying to login i am getting this error
The Operation couldn't be completed.(com.facebook.sdk error 2.0) error. iOS 6
This is mainly occurring when User's phone has preinstalled Facebook App, and when he tries to login into facebook through my app then i am getting error.
If I am logging out the account from the facebook app in iPhone, then it is working fine.
How can I overcome this issue,Kindly help me out to overcome this.
For reference, The code I am using is
- (void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen:
if (!error) {
// We have a valid session
NSLog(#"User session found");
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"FBFirstTime"];
[[NSUserDefaults standardUserDefaults] synchronize];
[self populateUserDetails];
if([[NSUserDefaults standardUserDefaults] boolForKey:#"FBFirstTime"])
{
}
else
{
NSLog(#"1st Time");
}
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[FBSession.activeSession closeAndClearTokenInformation];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Could not login with Facebook"
message:#"Facebook login failed. Please check your Facebook settings on your phone."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
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];
}
}
//
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
// NSArray *permissions = [[NSArray alloc] initWithObjects:#"email", #"user_likes", nil];
NSArray* permissions = [[NSArray alloc] initWithObjects:#"user_birthday",
#"user_about_me",
#"user_checkins",
#"user_hometown",
#"user_activities",
#"user_events",
nil];
return [FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
[self sessionStateChanged:session
state:state
error:error];
}];
}
//
- (void)populateUserDetails
{
if (FBSession.activeSession.isOpen) {
[[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
NSThread *contactsObjectsThread = [[NSThread alloc]initWithTarget:self selector:#selector(createUserContactsObjects) object:nil];
[contactsObjectsThread start];
[activityView stopAnimating];
}
}];
}
}
Check Single sign-on in off developer.facebook.com...
I had a similar problem, when you change your password or you change the fb permission of an app the fb token should change and you need to update your password or accept again the permission manually...
in the past there was a bug on the fb sdk that should be fixed, so my suggestion is update to the latest version and check for 'Sub Error' and check if the problem is the password, permission etc... and inform the user about the related action to restore the login
I was able to Fix the Issue finally, https://stackoverflow.com/a/13321162/1079929 by following this Answer
In Our developers.facebook, in our app, we need to add our BundleID in iOS Native App, and Facebook Login Enabled... that fixed the issue
Make sure you are using same bundle identifier in your app that you have given at developer.facebook.com when creating the app.
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
}];
In my App I used Facebook sdk 3.1 and using that I try to do wall Post.
Using This Code Snippet I can successfully wall post Image and Message on Friend Wall and on my own wall.I just change me/photos and friendId/photos.
-(IBAction)postPhoto:(id)sender
{
UIImage *image=[UIImage imageNamed:#"baby.jpg"];
NSArray *frndArray=[[NSArray alloc] initWithObjects:#"Friend ID", nil];
[self postImageOnFriendsWall:image FriendsArray:frndArray];
}
-(void)postImageOnFriendsWall:(UIImage*)image FriendsArray:(NSArray*)friends
{
AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
// if we don't have permission to announce, let's first address that
if ([appDelegate.session.permissions indexOfObject:#"publish_actions"] == NSNotFound)
{
NSArray *permissions =[NSArray arrayWithObjects:#"publish_actions",#"publish_stream",#"manage_friendlists", nil];
[FBSession setActiveSession:appDelegate.session];
[[FBSession activeSession] reauthorizeWithPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends completionHandler:^(FBSession *session, NSError *error)
{
if (!error)
{
// have the permission
[self postImageOnFriendsWall:image FriendsArray:friends];
}
else
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
}];
}
else
{
//post image
for (id<FBGraphUser> user in friends)
{
NSString* szMessage = #"Check out!";
NSString *userID = user;
NSLog(#"trying to post image of %# wall",userID);
NSMutableDictionary *postVariablesDictionary = [[NSMutableDictionary alloc] init];
[postVariablesDictionary setObject:UIImagePNGRepresentation(image) forKey:#"picture"];
[postVariablesDictionary setObject:szMessage forKey:#"message"];
[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:#"%#/photos",userID] parameters:postVariablesDictionary HTTPMethod:#"POST" completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
if (error)
{
//showing an alert for failure
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Facebook"
message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
else
{
//showing an alert for success
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Facebook"
message:#"Shared the photo successfully" delegate:nil cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}];
}
}
}
For Message wall post I used me/feed and its work but for Friend friendID/feed will give me Error: HTTP status code: 403 and In alert box i got com.facebook.sdk error 5.
So Please guide me m I doing anything wrong?, or What I have to do for wall post.
Here is solution,
I update my FB SDK 3.1 to 3.2 then import
#import <FacebookSDK/FacebookSDK.h>
then update
[[FBSession activeSession] requestNewPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {}];
in place of
[[FBSession activeSession] reauthorizeWithPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends completionHandler:^(FBSession *session, NSError *error){}];
and update
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"FRIEND ID", #"to",
#"text change", #"caption",
#"this is test message on ur wall", #"description",
#"https://website.com/share", #"link",
#"http://website.com/iossdk_logo.png", #"picture",
nil];
[FBWebDialogs presentFeedDialogModallyWithSession:nil
parameters:params
handler:
^(FBWebDialogResult result, NSURL *resultURL, NSError *error)
{}];
in place of
[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:#"%#/photos",userID] parameters:postVariablesDictionary HTTPMethod:#"POST" completionHandler:^(FBRequestConnection *connection, id result, NSError *error){}];
and i got Dialog box and after click on share Successfully post on FRIEND's Wall.
Hope this snippet help someone else.
I am not sure. Try this one:
me?fields=friends.fields(feed)
I need to post uiimage (screenshot taken from app) instead of url to post in facebook from facebook dialog along with user option to enter text. how it can be achieved. some help is appreciated.
You could try something like this to post the photo part. I'm sure the text is just another field.
#try {
// make sure your permissions are set
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"publish_stream",
nil];
[FBSession openActiveSessionWithPublishPermissions:permissions
defaultAudience:FBSessionDefaultAudienceOnlyMe
allowLoginUI:NO
completionHandler:^(FBSession *session, FBSessionState state, NSError *error){
NSLog(#"completion handler.");
}];
[FBRequestConnection startForUploadPhoto:imageToUpload
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
UIAlertView *tmp = [[UIAlertView alloc]
initWithTitle:#"Success"
message:#"Photo Uploaded!"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Ok", nil];
[tmp show];
} else {
UIAlertView *tmp = [[UIAlertView alloc]
initWithTitle:#"Error"
message:#"Error uploading image to Facebook."
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Ok", nil];
[tmp show];
}
}];
}
#catch (NSException *exception) {
NSLog(#"-----> !! ERROR UPLOADING IMAGE TO FACEBOOK !!");
}
to post image in facebook through fbconnect few steps need to follow with the fbconnect api.
need to login in facebook then it check about the access key and the expiry date.
if those are not nil, there it go to post the image i.e
NSData *imageData = UIImagePNGRepresentation(cellImageView.image);
NSMutableDictionary *params = [[NSMutableDictionary alloc]initWithObjectsAndKeys:#"app name",#"message",imageData,#"source", nil];
[facebook requestWithGraphPath:#"me/photos" andParams:params andHttpMethod:#"POST" andDelegate:self];
if not it go for the access key and expiry key and then to the image post code as written above.
for more download fbconnect api and look at the login and have a look on the code with brakepoints.
for this user need the login delegate and fb request delegate.
also don't forget to initialize facebook obj with app id and to set its delegate self.