I am getting an issue while posting a feed on Facebook using Facebook sdk in ios7.
I have copied the code from Facebook samples provided on Github. But whenever I tried to post on Facebook, a message appears as "An error occurred. Please try again later". And then I have to close the web view.
Please find the code below:
NSMutableDictionary *params123 = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"Roasted pumpkin seeds", #"name",
#"Healthy snack.", #"caption",
#"Crunchy pumpkin seeds roasted in butter and lightly salted.", #"description",
#"http://example.com/roasted_pumpkin_seeds", #"link",
#"http://i.imgur.com/g3Qc1HN.png", #"picture",
nil];
// Show the feed dialog
[FBWebDialogs presentFeedDialogModallyWithSession:nil
parameters:params123
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
// An error occurred, we need to handle the error
// See: https://developers.facebook.com/docs/ios/errors
NSLog(#"Error publishing story: %#", error.description);
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
// User cancelled.
NSLog(#"User cancelled.");
} else {
// Handle the publish feed callback
NSDictionary *urlParams = [self parseURLParams:[resultURL query]];
if (![urlParams valueForKey:#"post_id"]) {
// User cancelled.
NSLog(#"User cancelled.");
} else {
// User clicked the Share button
NSString *result = [NSString stringWithFormat: #"Posted story, id: %#", [urlParams valueForKey:#"post_id"]];
NSLog(#"result %#", result);
}
}
}
}];
}
Note: I am using the updated version of Facebook sdk for iOS 7
Why do you use a webdialog ?
Here is what I use
NSArray *urlsArray = [NSArray arrayWithObjects:#"myurl1", nil];
NSURL *imageURL = [NSURL URLWithString:#"http://url/to/image.png"];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
NSArray *imagesArray = [NSArray arrayWithObjects:image, nil];
[FBDialogs presentOSIntegratedShareDialogModallyFrom:self
session:nil
initialText:#"My message for facebook"
images:imagesArray
urls:urlsArray
handler:^(FBOSIntegratedShareDialogResult result, NSError *error) {
NSLog(#"Result : %u", result);
if (error != nil) {
NSLog(#"Error : %#", [error localizedDescription]);
}
}];
Related
I have sent facebook request. Its working fine, but I am getting request(notification) only in iPhone facebook App, not in Facebook web application. I want both Facebook native app and web application to receive notification. How can I do that?
#pragma Sending Facebook app request
- (NSDictionary*)parseURLParams:(NSString *)query {
NSArray *pairs = [query componentsSeparatedByString:#"&"];
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
for (NSString *pair in pairs) {
NSArray *kv = [pair componentsSeparatedByString:#"="];
NSString *val =
[[kv objectAtIndex:1]
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[params setObject:val forKey:[kv objectAtIndex:0]];
}
return params;
}
- (void)sendRequest {
NSError *error;
NSData *jsonData = [NSJSONSerialization
dataWithJSONObject:#{
#"social_karma": #"5",
#"badge_of_awesomeness": #"1"}
options:0
error:&error];
if (!jsonData) {
NSLog(#"JSON error: %#", error);
return;
}
NSString *giftStr = [[NSString alloc]
initWithData:jsonData
encoding:NSUTF8StringEncoding];
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
giftStr, #"data",
nil];
// Display the requests dialog
[FBWebDialogs
presentRequestsDialogModallyWithSession:nil
message:#"Learn how to make your iOS apps social."
title:nil
parameters:params
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
// Error launching the dialog or sending the request.
NSLog(#"Error sending request.");
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
// User clicked the "x" icon
NSLog(#"User canceled request.");
} else {
// Handle the send request callback
NSDictionary *urlParams = [self parseURLParams:[resultURL query]];
if (![urlParams valueForKey:#"request"]) {
// User clicked the Cancel button
NSLog(#"User canceled request.");
} else {
// User clicked the Send button
NSString *requestID = [urlParams valueForKey:#"request"];
NSLog(#"Request ID: %#", requestID);
}
}
}
}];
}
- (void)sendRequestClicked {
// Filter and only show friends using iOS
[self requestFriendsUsingDevice:#"iOS"];
}
- (void)sendRequest:(NSArray *) targeted {
NSError *error;
NSData *jsonData = [NSJSONSerialization
dataWithJSONObject:#{
#"social_karma": #"5",
#"badge_of_awesomeness": #"1"}
options:0
error:&error];
if (!jsonData) {
NSLog(#"JSON error: %#", error);
return;
}
NSString *giftStr = [[NSString alloc]
initWithData:jsonData
encoding:NSUTF8StringEncoding];
NSMutableDictionary* params =
[NSMutableDictionary dictionaryWithObjectsAndKeys:giftStr, #"data",
nil];
// Filter and only show targeted friends
if (targeted != nil && [targeted count] > 0) {
NSString *selectIDsStr = [targeted componentsJoinedByString:#","];
[params setObject:selectIDsStr forKey:#"suggestions"];
}
// Display the requests dialog
[FBWebDialogs
presentRequestsDialogModallyWithSession:nil
message:#"Learn how to make your iOS apps social."
title:nil
parameters:params
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
// Error launching the dialog or sending request.
NSLog(#"Error sending request.");
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
// User clicked the "x" icon
NSLog(#"User canceled request.");
} else {
// Handle the send request callback
NSDictionary *urlParams = [self parseURLParams:[resultURL query]];
if (![urlParams valueForKey:#"request"]) {
// User clicked the Cancel button
NSLog(#"User canceled request.");
} else {
// User clicked the Send button
NSString *requestID = [urlParams valueForKey:#"request"];
NSLog(#"Request ID: %#", requestID);
}
}
}
}];
}
- (void) requestFriendsUsingDevice:(NSString *)device {
NSMutableArray *deviceFilteredFriends = [[NSMutableArray alloc] init];
[FBRequestConnection startWithGraphPath:#"me/friends"
parameters:[NSDictionary
dictionaryWithObjectsAndKeys:
#"id,devices", #"fields",
nil]
HTTPMethod:nil
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
if (!error) {
// Get the result
NSArray *resultData = [result objectForKey:#"data"];
// Check we have data
if ([resultData count] > 0) {
// Loop through the friends returned
for (NSDictionary *friendObject in resultData) {
// Check if devices info available
if ([friendObject objectForKey:#"devices"]) {
NSArray *deviceData = [friendObject
objectForKey:#"devices"];
// Loop through list of devices
for (NSDictionary *deviceObject in deviceData) {
// Check if there is a device match
if ([device isEqualToString:
[deviceObject objectForKey:#"os"]]) {
// If there is a match, add it to the list
[deviceFilteredFriends addObject:
[friendObject objectForKey:#"id"]];
break;
}
}
}
}
}
}
// Send request
[self sendRequest:deviceFilteredFriends];
}];
}
You can only get notifications on Facebook web application if your app has a Facebook Canvas app implemented.
The invitable_friends API is only available for games that have a
Facebook Canvas app implementation using version 2.0 of the Graph API.
Check here the full documentation
Canvas is a frame in which to put your app or game directly on
Facebook.com on desktops and laptops.
Details about Canvas
Note: In the documentation you will find "your game", they mean "your game or your app".
I searched every where but not getting the single hint how to do that....i got some code also but it is not working ... can anyone suggest me any tutorial or sample code to do that !!! thanks in advance
i am trying following code::
-(void)inviteFriend:(CustomButton *)sender
{
NSString *str=[NSString stringWithFormat:#"%#/feed",sender.inviteUserId];
if (FBSession.activeSession.isOpen)
{
//UIImage *image = [UIImage imageNamed:#"testImage.png"];
hudApp = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hudApp.labelText = #"Page Sharing...";
[self performSelector:#selector(timeout:) withObject:nil afterDelay:60*5];
// NSString *fbMessage = [NSString stringWithFormat:#"test"];
NSString *fbMessage = #"hello testing";
NSMutableDictionary* params=[NSDictionary dictionaryWithObjectsAndKeys:fbMessage, #"message", FBSession.activeSession.accessToken, #"access_token", nil];
NSLog(#"feed::%#",str);
[FBRequestConnection startWithGraphPath:str
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result,NSError *error) {
NSLog(#"result::%#",result);
if(error)
{
NSLog(#"fail : %#",error.localizedDescription);
hudApp.labelText = [NSString stringWithFormat:#"%#",error.localizedDescription];
}
else
{
NSLog(#"Success facebook post");
hudApp.labelText = [NSString stringWithFormat:#"Success"];
// txtView.text = #"success";
NSLog(#"success");
}
hudApp.mode = MBProgressHUDModeCustomView;
[self performSelector:#selector(dismissHUD:) withObject:nil afterDelay:1.0];
}];
}
else
{
NSArray *permissions = [NSArray arrayWithObject:#"publish_stream"];
[FBSession openActiveSessionWithPermissions:permissions allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState state,NSError *error) {
NSLog(#"session.permissions ? : %#", session.permissions);
[self sessionDoneForPageShare:session state:state error:error withuserid:str];
}
];
}
}
-(void)sessionDoneForPageShare:(FBSession *)session state:(FBSessionState)state error:(NSError *)error withuserid :(NSString *)usreid
{
//UIImage *image = [UIImage imageNamed:#"testImage.png"];
NSLog(#"feed::%#",usreid);
hudApp = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hudApp.labelText = #"Page Sharing...";
[self performSelector:#selector(timeout:) withObject:nil afterDelay:60*5];
//NSString *fbMessage = [NSString stringWithFormat:#"test"];
NSString *fbMessage = #"hello testing";
NSLog(#"State : %d **** Facebook Message : %#",state,fbMessage);
// NSMutableDictionary * params = [NSMutableDictionary dictionaryWithObjectsAndKeys: fbMessage, #"message", nil];
NSMutableDictionary* params=[NSDictionary dictionaryWithObjectsAndKeys:fbMessage, #"message", FBSession.activeSession.accessToken, #"access_token", nil];
[FBRequestConnection startWithGraphPath:usreid
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(error)
{
NSLog(#"fail : %#",error.localizedDescription);
// txtView.text = [NSString stringWithFormat:#"%#",error.localizedDescription];
NSLog(#"%#",[NSString stringWithFormat:#"%#",error.localizedDescription]);
hudApp.labelText = [NSString stringWithFormat:#"%#",error.localizedDescription];
}
else
{
NSLog(#"Success facebook post");
hudApp.labelText = [NSString stringWithFormat:#"Success"];
//txtView.text = #"success";
NSLog(#"success");
}
hudApp.mode = MBProgressHUDModeCustomView;
[self performSelector:#selector(dismissHUD:) withObject:nil afterDelay:1.0];
}];
}
In order to post to a friend's wall, you need to make a request to /{friend_id}/feed. However, Facebook has disabled posting to friends' wall since February 6, 2013:
Removing ability to post to friends walls via Graph API
We will remove the ability to post to a user's friends' walls via the Graph
API. Specifically, posts against [user_id]/feed where [user_id] is
different from the session user, or stream.publish calls where the
target_id user is different from the session user, will fail. If you
want to allow people to post to their friends' timelines, invoke the
feed dialog. Stories that include friends via user mentions tagging or
action tagging will show up on the friend’s timeline (assuming the
friend approves the tag). For more info, see this blog post.
No matter what I try I cannot get my description to show up on Facebook. I used the debugger and all is well with the generated link and the URL is populated with the appropriate data. The picture is uploaded fine, but the description is not there. Is there something I need to setup in Facebook settings for the app?
Here is the relevant code:
- (id<FBPost>)outfitObjectForOutfit{
id<FBPost> result = (id<FBPost>)[FBGraphObject graphObject];
NSString *format =
#"http://mysite.mobi/app/fbOpen.php?"
#"og:title=%#&og:description=%%22%#%%22&"
#"og:caption=%%22%#%%22&"
#"og:image=http://mysite.mobi/images/transBlank.png&"
#"body=%#";
result.url = [NSString stringWithFormat:format,
#"New Post Title",fldDescription.text,fldDescription.text,fldDescription.text];
return result;
}
And the portion that publishes to FB:
- (void)postOpenGraphActionWithPhotoURL:(NSString*)photoURL
{
id<FBPost> outfitObject = [self outfitObjectForOutfit];
id<FBPostOutfit> action =
(id<FBPostOutfit>)[FBGraphObject graphObject];
action.outfit=outfitObject;
if (photoURL) {
NSMutableDictionary *image = [[NSMutableDictionary alloc] init];
[image setObject:photoURL forKey:#"url"];
NSMutableArray *images = [[NSMutableArray alloc] init];
[images addObject:image];
action.image = images;
}
[FBSettings setLoggingBehavior:[NSSet
setWithObjects:FBLoggingBehaviorFBRequests,
FBLoggingBehaviorFBURLConnections,
nil]];
NSLog(#"%#",action);
NSMutableDictionary *params = [NSMutableDictionary dictionary];
[params setObject:fldDescription.text forKey:#"message"];
[FBRequestConnection startForPostWithGraphPath:#"me/appnamespace:action"
graphObject:action
completionHandler:
^(FBRequestConnection *connection, id result, NSError *error) {
NSString *alertText;
if (!error) {
alertText = [NSString stringWithFormat:
#"Posted Open Graph action, id: %#",
[result objectForKey:#"id"]];
} else {
alertText = [NSString stringWithFormat:
#"error: domain = %#, code = %d",
error.domain, error.code];
NSLog(#"%#",error);
}
[[[UIAlertView alloc] initWithTitle:#"Result"
message:alertText
delegate:nil
cancelButtonTitle:#"Thanks!"
otherButtonTitles:nil]
show];
}
];
}
I figured out my problem. I was confusing what the Facebook examples did (activity publishing) with publishing to a user's wall. This was all that I had to do to get it to work:
NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
[params setObject:fldDescription.text forKey:#"message"];
[params setObject:UIImagePNGRepresentation(userImage) forKey:#"picture"];
[FBRequestConnection startWithGraphPath:#"me/photos"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error)
{
if (error) {
[[[UIAlertView alloc] initWithTitle:#"Result"
message:#"Sorry there was an error posting to Facebook."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil]
show];
}
}];
I should also mention that I had to go into the opengraph settings for my app and allow user messages and user generated photos.
I want to code a singleton for facebook integration with iOS 6.
I use Social and Accounts Frameworks.
This my FacebookData.h :
#class FacebookData;
#protocol FacebookDataDelegate <NSObject>
#optional
- (void)FacebookDataDidLoadRequest:(NSDictionary *)result;
- (void)FacebookDataDidFailToLoadRequest:(NSError *)error;
#end
#interface FacebookData : NSObject{
NSString *facebookAppID;
ACAccountStore *facebookAccountStore;
ACAccountType *facebookAccountType;
ACAccount *facebookAccount;
BOOL readPermissionsGranted;
BOOL RequestPermissionsGranted;
}
#property (nonatomic) id delegate;
+ (FacebookData*)sharedFacebookData;
- (void)setAppID:(NSString *)appID;
- (NSString *)currentAppID;
- (void)requestPermissions:(NSArray*)Permissions andLoadRequest:(NSString*)theRequest;
- (void)loadRequest:(NSString*)theRequest;
#end
The most important methods of my FacebookData.m :
- (void)requestPermissions:(NSArray*)Permissions andLoadRequest:(NSString*)theRequest{
if(!readPermissionsGranted){
__block NSArray *facebookPermissions = #[#"read_stream", #"email"];
__block NSDictionary *facebookOptions = #{ ACFacebookAppIdKey : facebookAppID,
ACFacebookAudienceKey : ACFacebookAudienceFriends,
ACFacebookPermissionsKey : facebookPermissions};
[facebookAccountStore requestAccessToAccountsWithType:facebookAccountType options:facebookOptions completion:^(BOOL granted, NSError *error)
{
if (granted) {
readPermissionsGranted = YES;
[self requestPermissions:Permissions andLoadRequest:theRequest];
}
// If permission are not granted to read.
if (!granted)
{
NSLog(#"Read permission error: %#", [error localizedDescription]);
[self.delegate FacebookDataDidFailToLoadRequest:error];
readPermissionsGranted = NO;
if ([[error localizedDescription] isEqualToString:#"The operation couldn’t be completed. (com.apple.accounts error 6.)"])
{
[self performSelectorOnMainThread:#selector(showError) withObject:error waitUntilDone:NO];
}
}
}];
}else{
__block NSArray *facebookPermissions = [NSArray arrayWithArray:Permissions];
__block NSDictionary *facebookOptions = #{ ACFacebookAppIdKey : facebookAppID,
ACFacebookAudienceKey : ACFacebookAudienceFriends,
ACFacebookPermissionsKey : facebookPermissions};
[facebookAccountStore requestAccessToAccountsWithType:facebookAccountType options:facebookOptions completion:^(BOOL granted2, NSError *error)
{
if (granted2)
{
RequestPermissionsGranted = YES;
// Create the facebook account
facebookAccount = [[ACAccount alloc] initWithAccountType:facebookAccountType];
NSArray *arrayOfAccounts = [facebookAccountStore accountsWithAccountType:facebookAccountType];
facebookAccount = [arrayOfAccounts lastObject];
[self loadRequest:theRequest];
NSLog(#"Permission granted");
}
if (!granted2)
{
NSLog(#"Request permission error: %#", [error localizedDescription]);
[self.delegate FacebookDataDidFailToLoadRequest:error];
RequestPermissionsGranted = NO;
}
}];
}
}
- (void)loadRequest:(NSString*)theRequest{
__block NSDictionary *result= [[NSDictionary alloc]init];
// Create the URL to the end point
NSURL *theURL = [NSURL URLWithString:theRequest];
// Create the SLReqeust
SLRequest *slRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook requestMethod:SLRequestMethodGET URL:theURL parameters:nil];
// Set the account
[slRequest setAccount:facebookAccount];
// Perform the request
[slRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if (error)
{
// If there is an error we populate the error string with error
__block NSString *errorString = [NSString stringWithFormat:#"%#", [error localizedDescription]];
NSLog(#"Error: %#", errorString);
[self.delegate FacebookDataDidFailToLoadRequest:error];
} else
{
NSLog(#"HTTP Response: %i", [urlResponse statusCode]);
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
result = jsonResponse;
[self.delegate FacebookDataDidLoadRequest:jsonResponse];
}
}];
}
I use this singleton like this :
FacebookData *data = [FacebookData sharedFacebookData];
data.delegate = self;
[data setAppID:APPIDKEY];
[data requestPermissions:#[#"friends_location"] andLoadRequest:#"https://graph.facebook.com/me/friends?fields=id,name,location"];
This request with this permissions fails whereas the same method with permissions :#[#"email"] and request: https://graph.facebook.com/me/friends works perfectly.
This is the error that I can see in the console :
error = {
code = 2500;
message = "An active access token must be used to query information about the current user.";
type = OAuthException;
};
I can't find where the bug is, I don't know how to use tokens with these frameworks.
Thanks for your help !
IMO your LoadRequest URL is not correct
andLoadRequest:#"https://graph.facebook.com/me/friends?fields=id,name,location"];
SLRequest gives an oauth error even though its real problem with the URL. SLRequest doesn't support "?fields=id,name,location" directly in URL. You need to pass them as parameter in SLRequest
See the example below:
NSString* queryString = NULL;
queryString = [NSString stringWithFormat:#"https://graph.facebook.com/me/friends", nil];
NSURL *friendsRequestURL = [NSURL URLWithString:queryString];
SLRequest *friendsRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET URL:friendsRequestURL
parameters:#{#"fields":#"id,name,location"}];
PS: I was facing the similar problem last night and cursing the facebook for given wrong error statement. But finally able to solve it at the end. :)
I am trying to tag some of my friends in my wall post and I am sending the following parameters but this posts to my wall the FB ids I provide do not get attached to the post...
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"Test 2 ",#"message",
#"100004311843201 , 1039844409", #"to",
#"http://www.google.com", #"link",
#"Test", #"name",
nil];
[self.appDelegate.facebook requestWithGraphPath:#"me/feed" andParams:params andHttpMethod:#"POST" andDelegate:self];
Any help is appreciated...
To tag a friend in ur fb status ..you need "facebook id" of your friend by using FBFriendPickerViewController and "place id" using FBPlacePickerViewController.
Following code will help you.
NSString *apiPath = nil;
apiPath = #"me/feed";
if(![self.selectedPlaceID isEqualToString:#""]) {
[params setObject:_selectedPlaceID forKey:#"place"];
}
NSString *tag = nil;
if(mSelectedFriends != nil){
for (NSDictionary *user in mSelectedFriends) {
tag = [[NSString alloc] initWithFormat:#"%#",[user objectForKey:#"id"] ];
[tags addObject:tag];
}
NSString *friendIdsSeparation=[tags componentsJoinedByString:#","];
NSString *friendIds = [[NSString alloc] initWithFormat:#"[%#]",friendIdsSeparation ];
[params setObject:friendIds forKey:#"tags"];
}
FBRequest *request = [[[FBRequest alloc] initWithSession:_fbSession graphPath:apiPath parameters:params HTTPMethod:#"POST"] autorelease];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
[SVProgressHUD dismiss];
if (error) {
NSLog(#"Error ===== %#",error.description);
if (_delegate != nil) {
[_delegate facebookConnectFail:error requestType:FBRequestTypePostOnWall];
}else{
NSLog(#"Error ===== %#",error.description);
}
}else{
if (_delegate != nil) {
[_delegate faceboookConnectSuccess:self requestType:FBRequestTypePostOnWall];
}
}