can change facebook app invitation text using graph api - ios

Can we change facebook app invitation text using facebook Graph api ?
Generally this has format - "Inviter name sent you a request", can we replace this text to our own ?
(This get displayed as a notification on fb wall.)
I am using below code -
- (void)load:(BOOL)NeedToSendAppRequest AndMessage:(NSString*)message AndFriendID:(NSString*)friendID {
NSString *urlString = nil;
isNeedToSendAppRequest = NeedToSendAppRequest;
if (NeedToSendAppRequest) {
NSString *redirectUrlString = FACEBOOK_REDIRECT_URL;
NSString *authFormatString = #"https://m.facebook.com/dialog/apprequests?app_id=%#&target_url=fb%#&to=%#&message=%#&redirect_uri=%#";
urlString = [NSString stringWithFormat:authFormatString, _apiKey, _apiKey,friendID,message,redirectUrlString];
}else{
NSString *redirectUrlString = #"http://www.facebook.com/connect/login_success.html";
NSString *authFormatString = #"https://graph.facebook.com/oauth/authorize?client_id=%#&redirect_uri=%#&scope=%#&type=user_agent&display=touch";
urlString = [NSString stringWithFormat:authFormatString, _apiKey, redirectUrlString, _requestedPermissions];
}
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[_webView loadRequest:request];
}

Check out the sample below - friendToInviteCSVString is a comma separated string of friend FB IDs that you want to invite. You can set a custom invite message in the message key of the parameter dictionary.
This is using the 3.x FB iOS SDK, by the way:
//Remove last comma from CSV string
friendToInviteCSVString = [friendToInviteCSVString stringByTrimmingCharactersInSet:[NSCharacterSet punctuationCharacterSet]];
NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithObjectsAndKeys:
NSLocalizedString(#"Check out this awesome app.", #"Check out this awesome app."), #"message",
friendToInviteCSVString, #"to", nil];
//Do FB invites
DDLogVerbose(#"Active fb session: %#", [FBSession activeSession]);
[FBWebDialogs presentDialogModallyWithSession:[FBSession activeSession] dialog:#"apprequests" parameters:parameters handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error)
{
DDLogVerbose(#"Facebook closed dialog with result: %d, URL: %#, error: %#", result, resultURL, error);
}];
EDIT:
Ok so I went digging around in my legacy code and here's a sample using FBDialog which is what's available in the SDK version you're using. First you need a Facebook object:
Facebook *facebook = [[Facebook alloc] initWithAppId:kFBAppID andDelegate:self];
//Check if token is valid
if (FBSession.activeSession.accessToken)
{
DLog(#"Init FB with activeSession, token: %# and expirationDate: %#", FBSession.activeSession.accessToken, FBSession.activeSession.expirationDate);
self.facebook.accessToken = FBSession.activeSession.accessToken;
self.facebook.expirationDate = FBSession.activeSession.expirationDate;
}
else
{
//No FB Token, do something here - ask user for permission, etc
}
NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithObjectsAndKeys:
NSLocalizedString(#"Check out this awesome app.", #"Facebook apprequest invite message"), #"message", friendsToInvite, #"to", nil];
[self.facebook dialog:#"apprequests" andParams:parameters andDelegate:self];

Related

How do I inject deep linking query parameters into appLinkData when using Facebook app links on iOS?

My question is predicated on Jason Clark’s statement at f8 2014 that app links is designed to sit side by side well with deep linking technologies. I have a word game app published in 2013 to Canada and Australia using Facebook’s authentication but without deep linking. For the US market launch my intent was to add Facebook deep linking. Managed with the request and feed dialogs to send the Match Identifier UUID for both initiating a match and then bragging about the match (FriendSmash example) at that time to open the game on that match. My day job got in the way and I did not have time to finish QA and support a launch to the US. Last summer I upgraded SDKs (Facebook 3.14) and the url query no longer contained the string ‘notif’ to allow me to parse for the match Id. Therefore, I switched from using [FBSession.activeSession handleOpenURL:url] to the current [FBAppCall handleOpenURL:url …] and some other code from the new FriendSmash example. However, the url passed from the Facebook app no longer contains the ‘ref’ and therefore not the ‘notif’ which was the method documented to utilize my deep linking content. I have since updated my project to Facebook iOS SDK 3.21 (predicated in part by other SDKs, e.g. AWS not supporting arm64).
I currently use the following code to send the brag
- (void) sendBrag
{
// This function will invoke the Feed Dialog to post to a user's Timeline and News Feed
// It will attemnt to use the Facebook Native Share dialog
// If that's not supported we'll fall back to the web based dialog.
NSArray *friend = [[NSArray alloc] initWithObjects: bragMatch.opponentFacebookId, nil];
NSString *linkURL = [NSString stringWithFormat:#"http://www.ruleofwords.com/?deeplink_matchno=%#", bragMatch.initiatorMatchNo];
//NSString *linkURL = [NSString stringWithFormat:#"http://www.ruleofwords.com"];
NSString *pictureURL = #"https://pacific-castle-1361.herokuapp.com/rowappicon.png";
NSMutableString *msg = [[NSMutableString alloc]
initWithString:#"Just scored 0 points in Rule of Words. Good luck trying to beat that."];
[msg replaceOccurrencesOfString:#"0" withString:bragMatch.initiatorMatchPoints
options:NSBackwardsSearch range: NSMakeRange(0, [msg length])];
// Prepare the native share dialog parameters
FBLinkShareParams *shareParams = [[FBLinkShareParams alloc] init];
shareParams.friends = friend;
shareParams.link = [NSURL URLWithString:linkURL];
shareParams.name = #"Rule of Words Bragging Rights";
shareParams.caption= msg;
shareParams.picture= [NSURL URLWithString:pictureURL];
shareParams.linkDescription = #"Rule of Words, the contagious photography word social game on iPhone.";
if ([FBDialogs canPresentShareDialogWithParams:shareParams]){
[FBDialogs presentShareDialogWithParams:shareParams
clientState:nil
handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
if(error) {
NSLog(#"Error publishing story.");
} else if (results[#"completionGesture"] && [results[#"completionGesture"] isEqualToString:#"cancel"]) {
NSLog(#"User canceled story publishing.");
} else {
NSLog(#"Story published.");
}
}];
} else {
// Prepare the web dialog parameters
NSDictionary *params = #{
#"to": bragMatch.opponentFacebookId,
#"name" : shareParams.name,
#"caption" : shareParams.caption,
#"description" : shareParams.linkDescription,
#"picture" : pictureURL,
#"link" : linkURL
};
// Invoke the dialog
[FBWebDialogs presentFeedDialogModallyWithSession:nil
parameters:params
handler:
^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
NSLog(#"Error publishing story %#.", error);
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
NSLog(#"User canceled story publishing.");
} else {
NSLog(#"Story published.");
}
}}];
}
}
(Aside - In my stepping through the sendBrag code the FBDialogs canPresentShareDialogWithParams always fails so that every time it defaults to a feed dialog. Anyone know what is the state is where the share dialog works? )
Then in my AppDelegate I have…
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
NSLog(#"app is %# and url is %# and sourceApp is %#", application, url, sourceApplication);
// attempt to extract a token from the url
return [FBAppCall handleOpenURL:url
sourceApplication:sourceApplication
fallbackHandler:^(FBAppCall *call) {
// If there is an active session
if (FBSession.activeSession.isOpen) {
// Check the incoming link
[self handleAppLinkData:call.appLinkData];
} else {
NSLog(#"Access Token is %#", call.accessTokenData);
if (call.accessTokenData) {
// If token data is passed in and there's
// no active session.
if ([self handleAppLinkToken:call.accessTokenData]) {
// Attempt to open the session using the
// cached token and if successful then
// check the incoming link
[self handleAppLinkData:call.appLinkData];
}
}
}
}];
- (void) handleAppLinkData:(FBAppLinkData *)appLinkData {
NSURL *targetURL = appLinkData.targetURL;
if (targetURL) {
//NSURL *targetURL = [NSURL URLWithString:targetURLString];
NSDictionary *targetParams = [self parseURLParams:[targetURL query]];
NSString *ref = [targetParams valueForKey:#"ref"];
// Check if ref parm is among incoming news feed link, otw attribution link
if ([ref isEqualToString:#"notif"]) {
// Get the request id
NSString *requestIDParam = targetParams[#"request_ids"];
NSArray *requestIDs = [requestIDParam
componentsSeparatedByString:#","];
// Get data (of last request) from Graph API call to request id endpoint
//
[self notificationGet:requestIDs[[requestIDs count]-1]];
}
}
}
- (void) notificationGet:(NSString *)requestid {
__block NSString *title;
__block NSString *message;
[FBRequestConnection startWithGraphPath:requestid
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
if (! error) {
if (result[#"data"])
{
title = [NSString stringWithFormat:
#"%# requests a match!", result[#"from"][#"name"]];
NSString *jsonString = result[#"data"];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
if (!jsonData) {
NSLog(#"JSON decode error: %#", error);
return;
}
NSError *jsonError = nil;
NSDictionary *requestData =[NSJSONSerialization JSONObjectWithData:jsonData options:0
error:&jsonError];
if (jsonError) {
NSLog(#"JSON decode error: %#", error);
return;
}
message = [NSString stringWithFormat:#"Match #: %#, Flashes: %#",
requestData[#"deeplink_matchno"],
requestData[#"flashes_gifted"]];
// set global opponentFacebookId for bragging
[[rowGlobals sharedGlobalVars] setRowGlobal:requestData[#"deeplink_matchno"]
forKey:#"deeplink_matchno"] ;
// Set up FB Deep Link Notification
// homeViewController is registered for notification
[[NSNotificationCenter defaultCenter]
postNotificationName:FBDeepLinkNotification
object:requestData[#"deeplink_matchno"]];
NSLog(#"successfully posted DeepLink notification") ;
} else {
title = [NSString stringWithFormat:#"%# sent you a request", result[#"from"][#"name"]];
message = result[#"message"];
}
// Delete the request notification
[self notificationClear:result[#"id"]];
} else {
title = #"General Deep Link Error" ;
message = #"Error occured with Facebook FBRequest Connection. This Facebook notification likely has been previously processed." ;
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil,
nil];
[alert show];
}];
}
Now I recognize I have some clean up to align the dialog setup with how I parse appLinkData to get the matchId UUID for my NSNotification to open on the game, but I am not getting that far to bother cleaning it up.
I have tried many meta tags on my site but at the moment I am just using
<meta property=”al:ios:url” content=”ruleofwords”>
where ruleofwords is a custom URL I added to my app’s plist.
but I cannot seem to put together any URL other than
NSString *linkURL = [NSString stringWithFormat:#"http://www.ruleofwords.com"];
which will launch my game by clicking on the Facebook link…
When I use anything like
NSString *urlLink = [NSString stringWithFormat:#"https://www.ruleofwords.com/?deeplink_matchNo=%#", bragMatch.initiatorMatchNo];
Then Facebook will only launch my web page without the custom URL link to my game.
Moreover, Facebook no longer launches it directly; it brings up my web page with an added link displayed as the offset brackets app Links logo.(Although not explicit it does technically follow the Facebook flow diagram). Touching this app Link logo does launch my game. This seems to be the case whether I have the meta tag on my website or not (now I may have other problems since we are only using Godaddy website builder).
Previously with the request dialog I had the ability to populate values such as #”data” with things like my match Id and gifts
NSData *jsonData = [NSJSONSerialization
dataWithJSONObject:#{
#"deeplink_matchno": bragMatch.initiatorMatchNo,
#"flashes_gifted": #"0"}
options:0
error:&error];
if (!jsonData) {
NSLog(#"JSON error: %#", error);
return;
}
NSString *challengeStr = [[NSString alloc]
initWithData:jsonData
encoding:NSUTF8StringEncoding];
NSMutableDictionary *params =
[NSMutableDictionary dictionaryWithObjectsAndKeys:
bragMatch.opponentFacebookId, #"to",
#"Rule of Words Bragging", #"name",
msg, #"caption",
#"Rule of Words, the contagious photography word social game on iPhone.",
#"description",
urlLink, #"link",
#"https://pacific-castle-6969.herokuapp.com/rowappicon.png", #"picture",
challengeStr, #"data",
nil];
// Invoke the dialog
//[self.facebook dialog:#"feed" andParams:params andDelegate:self];
//[FBWebDialogs presentFeedDialogModallyWithSession:nil
[FBWebDialogs presentRequestsDialogModallyWithSession:nil
message:msg
title:nil
parameters:params
handler:
^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
// Case A: Error launching the dialog or publishing story.
NSString *errormsg = [NSString stringWithFormat:#"Error encountered posting Facebook brag with error %#", error.localizedDescription];
NSLog(#"%#", errormsg);
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Facebook Brag Error"
message:errormsg
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles: nil];
[alert show];
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
// Case B: User clicked the "x" icon
NSLog(#"Player canceled Facebook brag post via x icon.");
} else {
// Case C: Dialog shown and the user clicks Cancel or Share
NSDictionary *urlParams = [self parseURLParams:[resultURL query]];
//if (![urlParams valueForKey:#"post_id"]) {
if ([urlParams valueForKey:#"error_code"]) {
// User clicked the Cancel button
NSLog(#"error message is %#", [urlParams valueForKey:#"error_message"]);
NSLog(#"Player canceled Facebook brag post via Cancel button.");
} else {
// User clicked the Share button
//NSString *postID = [urlParams valueForKey:#"post_id"];
NSString *postID = [urlParams valueForKey:#"request"];
NSLog(#"Player Successfuly Posted RoW Match via Facebook brag, id: %#", postID);
}
}
}
}];
However, I no longer have al_applink_data in the passed URL for this request dialog, it just has an access_token with the original custom URL.
url is fb407545862655947://authorize/#access_token=CAAFyqSpfj8sBAGxahmdTCl1D9fs5hZBt3OfKP2MHCtM8STHadqEjlyFnXDTNHScjsxZCI6q0H8ZAppNSqJIJt83uN4LemkfklLjOdPTv3JZBtg3xTVZBKOhzdOMaZCGob5x2FPddZBzmaZBhIaE8dIgNqPfi9IlEuwQ2oHq6tEgA1w1pNESnHuDyK9gD7vswAC93nO7cCmCT4KBgxI22UDB3nINYZA058g8AZD&expires_in=3600 and sourceApp is com.facebook.Facebook
When I add the #”data” param with
[FBWebDialogs presentFeedDialogModallyWithSession:…]
although this argument is accepted by the feed dialog I the url does not get my match UUID or anything extra from my #”data” param…
url is ruleofwords:///?al_applink_data=%7B%22target_url%22%3A%22http%3A%5C%2F%5C%2Fwww.ruleofwords.com%5C%2F%22%2C%22extras%22%3A%7B%22fb_ref%22%3A%22Default%22%7D%2C%22referer_app_link%22%3A%7B%22url%22%3A%22fb%3A%5C%2F%5C%2F%5C%2F%3Fbacktrack_id%3Ddlr5p6iu_6a-OeUn%22%2C%22app_name%22%3A%22Facebook%22%7D%7D and sourceApp is com.facebook.Facebook
So I am at a loss how I am supposed to inject content specific information so that I can open my game with the match, which the opponent has requested or bragged about. I probably would have given up a long time ago but I did once have deep linking working (SDK 3.5?). I am wondering if I should be at another release level of the SDK for deep linking. It seems like the Facebook platform has significantly changed how it packages appLinkData. And although Facebook’s documentation has improved over the past two years, many of the examples which are required to put this all together do not seem to be referring to the same level of SDK. So Facebook how do I inject content into appLinkData so I can support deep linking with SDK 3.21? I thought about adding the Bolts framework but Jason implied it was designed for outlinking apps, which is not my case.
I can directly type in my iPhone Safari something like ‘ruleofwords://matchId=UUID’ and get the app delegate to parse out the [url query] so I could probably implement deep linking with push notifications, but I still like the ability to have a Facebook user tap on a link and launch the specific match directly.

FBSession Error validating access token: Session does not match current stored session

I'm trying to use Facebook SDK in my application. My application is using Salesforce SDK to logging with Salesforce and the user can use Facebook to logging in my application.
From Salesforce can take the Facebook access token when the user logs in with Facebook. I use this access token to open a session with the object FBSession.
This is the code that I'm using to open a session:
NSArray *newPermission = [NSArray arrayWithObjects:#"user_friends",#"email", nil];
NSMutableDictionary *tokenInformationDictionary = [NSMutableDictionary new];
tokenInformationDictionary[#"com.facebook.sdk:TokenInformationExpirationDateKey"] = [NSDate dateWithTimeIntervalSinceNow: 3600];;
tokenInformationDictionary[#"com.facebook.sdk:TokenInformationRefreshDateKey"] = [NSDate date];
tokenInformationDictionary[#"com.facebook.sdk:TokenInformationTokenKey"] = fbAccessToken;
tokenInformationDictionary[#"com.facebook.sdk:TokenInformationPermissionsKey"] = newPermission;
tokenInformationDictionary[#"com.facebook.sdk:TokenInformationLoginTypeLoginKey"] = #0;
FBAccessTokenData *accesToken = [FBAccessTokenData createTokenFromDictionary: tokenInformationDictionary];
[[FBSession activeSession] openFromAccessTokenData:accesToken completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
}];
I'm trying to publish links and get my friends list.
To publish I use this code:
NSDictionary *params = #{
#"name" : [NSString stringWithFormat:NSLocalizedString(#"FBNameFormat", nil), [dicRecord objectForKey:#"Name"], [[dicRecord objectForKey:#"Store__r"] objectForKey:#"Name"]],
#"caption" : [NSString stringWithFormat:NSLocalizedString(#"FBCaptionFormat", nil), [dicRecord objectForKey:#"Name"], [[dicRecord objectForKey:#"Store__r"] objectForKey:#"Name"]],
#"description" : NSLocalizedString(#"FBDescription", nil), //#"Welcome to iOS world",
#"picture" : [dicRecord objectForKey:#"Image__c"],
#"link" : [NSString stringWithFormat:NSLocalizedString(#"FBDishUrl", nil), [dicRecord objectForKey:#"Id"]]//a00w000000V0TK9",
};
// Invoke the dialog
[FBWebDialogs presentFeedDialogModallyWithSession:nil parameters:params handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
NSLog(#"Error publishing story.");
//[self.indicator stopAnimating];
} else if (result == FBWebDialogResultDialogCompleted){
if ([isSuggested isEqual:[NSNumber numberWithInt:-1]]){
NSMutableDictionary *diccionario = [[NSMutableDictionary alloc] init];
}
}
}];
1)
That only works if I close and open again my apps, using
[FBSession.activeSession closeAndClearTokenInformation];
in completionHandler of openFromAccessTokenData.
Is there a way to make this work without having to close and re-open my app?
2)
When I try to get my Friend list using this code:
FBRequest *reqMyFriends = [FBRequest requestForMyFriends];
reqMyFriends.session = FBSession.activeSession;
[reqMyFriends startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary* result,NSError *error) {
if (!error){
NSArray* friends = [result objectForKey:#"data"];
}
}];
I get this error:
error =
{
code = 190;
"error_subcode" = 460;
message = "Error validating access token: Session does not match current stored session. This may be because the user changed the password since the time the session was created or Facebook has changed the session for security reasons.";
type = OAuthException;
};
code = 400;
Why do I get this error?

OAuthException/ code = 2500/ message = "An active access token must be used to query information about the current user."

I am trying to get data (like name,gender,birthday, profile picture etc) of the user that is logged in. I have tried following two codes, shown below:
//first: Create request for user's Facebook data
FBRequest *request = [FBRequest requestForMe];
// Send request to Facebook
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
NSLog(#"%#", error);
if (!error) {
// result is a dictionary with the user's Facebook data
NSDictionary *userData = (NSDictionary *)result;
NSLog(#"%#....",userData);
_facebookID = userData[#"id"];
_name = userData[#"name"];
_location = userData[#"location"][#"name"];
_gender = userData[#"gender"];
_birthday = userData[#"birthday"];
NSLog(#"%#",_name);
_picutreURL = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large&return_ssl_resources=1", _facebookID]];
self.nameField.text=_name;
self.profilePicture.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:_picutreURL]];
self.profileInfo.text=[NSString stringWithFormat:#"%#, Live in %# , Born on %#",_gender,_location,_birthday];
}
}];
// 2nd:Fetch user data
[FBRequestConnection
startForMeWithCompletionHandler:^(FBRequestConnection *connection,
id<FBGraphUser> user,
NSError *error) {
if (!error) {
NSString *userInfo = #"";
// Example: typed access (name)
// - no special permissions required
userInfo = [userInfo
stringByAppendingString:
[NSString stringWithFormat:#"Name: %#\n\n",
user.name]];
// Example: typed access, (birthday)
// - requires user_birthday permission
userInfo = [userInfo
stringByAppendingString:
[NSString stringWithFormat:#"Birthday: %#\n\n",
user.birthday]];
// Example: partially typed access, to location field,
// name key (location)
// - requires user_location permission
userInfo = [userInfo
stringByAppendingString:
[NSString stringWithFormat:#"Location: %#\n\n",
user.location[#"name"]]];
// Example: access via key (locale)
// - no special permissions required
userInfo = [userInfo
stringByAppendingString:
[NSString stringWithFormat:#"Locale: %#\n\n",
user[#"locale"]]];
// Example: access via key for array (languages)
// - requires user_likes permission
if (user[#"languages"]) {
NSArray *languages = user[#"languages"];
NSMutableArray *languageNames = [[NSMutableArray alloc] init];
for (int i = 0; i < [languages count]; i++) {
languageNames[i] = languages[i][#"name"];
}
userInfo = [userInfo
stringByAppendingString:
[NSString stringWithFormat:#"Languages: %#\n\n",
languageNames]];
}
// Display the user info
NSLog(#"%#",userInfo);
}
}];
But I get null string in output and detected this error:
Error Domain=com.facebook.sdk Code=5 "The operation couldn’t be completed. (com.facebook.sdk error 5.)" UserInfo=0x9499320 {com.facebook.sdk:ParsedJSONResponseKey={
body = {
error = {
code = 2500;
message = "An active access token must be used to query information about the current user.";
type = OAuthException;
};
};
code = 400;
}, com.facebook.sdk:HTTPStatusCode=400}
What should I do?
I believe I had the same problem, and the way I just got it working was to add
FBSession.activeSession = fbSession;
once the initial handler came back successfully. (fbSession is whatever variable you have with the facebook session in it.) I just randomly stumbled upon this (I think from another StackOverflow post). But I don't see it in the docs, and by grepping, it doesn't seem to be in any of the Sample apps. So maybe there's a larger issue with my code that I'm not seeing? I'd be interested to hear how others avoid setting the activeSession, and still are able to run startForMeWithCompletionHandler.

facebook app requests notifications doesn't appear

Actually I need to add the app requests concept in my app. For that I have used following code :
[FBWebDialogs
presentRequestsDialogModallyWithSession:[FBSession activeSession]
message:#"Try this app"
title:nil
parameters:params
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
NSLog(#"Error sending request.");
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
NSLog(#"User canceled request.");
} else {
NSDictionary *urlParams = [self parseURLParams:[resultURL query]];
if (![urlParams valueForKey:#"request"]) {
NSLog(#"User canceled request.");
} else {
NSString *requestID = [urlParams valueForKey:#"request"];
NSLog(#"Request ID: %#", requestID);
}
}
}
}];
- (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[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
params[kv[0]] = val;
}
return params;
}
I also looked upon this facebook documentation App requests
But when I send request to any of my friend, I got the request id but that notification doesn't appear on my friend facebook account. What I am doing wrong with above code?
Requests are not shown in notifications. There are only viewable in private by the user they are sent to. The will show up on the Requests page or as a notification to the user.
You can do what you are asking but it is a bit of a hassle.
There is nothing wrong with your request code from what I can see.
But what you probably don't have - and need is to add an "App on Facebook" in your settings page for your app.
It is where you have added "iOS" as a platform. You need to add "App on Facebook" as a platform as well and for this you will need 2 things. A website url (any site you control) and a url which is protected by https.
Once you have this and put this into "Canvas URL" and "Secure Canvas URL" in the Facebook settings the notifications sent by the app will show up on the home-screen for the tergeted user(s).
you Set enable in sandbox mode in facebook developer
Here's Visit https://www.facebook.com/login.php?next=https%3A%2F%2Fdevelopers.facebook.com%2Fapps
In your Facebook go to games->apps->app request and see app notification

iOS facebook integration - sending and receiving requests

I use a facebook api to connect to facebook and send request via native dialogs provided by the api.
I followed the sample posted in the docs on developers.facebook.com
But I have following problem sending requests :
1. The requests are not shown in notifications - only in application center - In this case i think that it is a problem of that the app is in sandbox and not posted to APPSTORE
I succesfully send request to facebook server with right fbUser id. But when I want to receive the notification in app here comes the problem :
Following the docs as an authorized user I should se
this in open url method:
fb[APP_ID]://authorize#expires_in=[ACCESS_TOKEN_EXPIRATION]
&access_token=[USER_ACCESS_TOKEN]
&target_url=https://apps.facebook.com/[APP_NAME_SPACE]/?request_ids=
[COMMA_SEPARATED_REQUESTIDs]&ref=notif&app_request_type=user_to_user
But i can see only plain login without targer url .... I can see session expiration date, fb app id, access token and so on. But no target url?
So basically what the target_url is?
How it should be set?
What i have to include when sending request?
In addition :
application handle open url method is called properly.
checkRequests method is also called properly after app becomes active.
Please do not link me to the docs. I have read it moreless 50 times and didn't find any reasonable solution...
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
// attempt to extract a token from the url
self.openedURL = url;
NSLog(#"%#",url);
return [FBSession.activeSession handleOpenURL:url];
}
- (void)sendRequest {
FBSBJSON *jsonWriter = [FBSBJSON new];
NSDictionary *gift = [NSDictionary dictionaryWithObjectsAndKeys:
#"5", #"points",
#"1", #"badge",
nil];
NSString *giftStr = [jsonWriter stringWithObject:gift];
NSMutableDictionary* params =
[NSMutableDictionary dictionaryWithObjectsAndKeys:
#"Hi from test app", #"message",
giftStr, #"data",
nil];
[self.facebook dialog:#"apprequests"
andParams:params
andDelegate:self];
}
// Handle the request call back
- (void)dialogCompleteWithUrl:(NSURL *)url {
NSDictionary *params = [self parseURLParams:[url query]];
NSString *requestID = [params valueForKey:#"request"];
NSLog(#"Request ID: %#", requestID);
}
-(FBSession*)returnSession{
return self.session;
}
/*
* Helper function to get the request data
*/
- (void) notificationGet:(NSString *)requestid {
[FBRequestConnection startWithGraphPath:requestid
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
if (!error) {
NSString *title;
NSString *message;
if ([result objectForKey:#"data"]) {
title = [NSString
stringWithFormat:#"%# sent you a gift",
[[result objectForKey:#"from"]
objectForKey:#"name"]];
FBSBJSON *jsonParser = [FBSBJSON new];
NSDictionary *requestData =
[jsonParser
objectWithString:[result objectForKey:#"data"]];
message =
[NSString stringWithFormat:#"Badge: %#, Karma: %#",
[requestData objectForKey:#"badge"],
[requestData objectForKey:#"points"]];
} else {
title = [NSString
stringWithFormat:#"%# sent you a request",
[[result objectForKey:#"from"] objectForKey:#"name"]];
message = [NSString stringWithString:
[result objectForKey:#"message"]];
}
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:title
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil,
nil];
[alert show];
// Delete the request notification
[self notificationClear:[result objectForKey:#"id"]];
}
}];
}
/*
* Helper function to check incoming URL
*/
- (void) checkIncomingNotification {
if (self.openedURL) {
NSString *query = [self.openedURL fragment];
if (!query) {
query = [self.openedURL query];
}
NSDictionary *params = [self parseURLParams:query];
for (NSString * str in [params allKeys]) {
NSLog(#"key %#", str);
}
// Check target URL exists
NSString *targetURLString = [params valueForKey:#"target_url"];
if (targetURLString) {
NSURL *targetURL = [NSURL URLWithString:targetURLString];
NSDictionary *targetParams = [self parseURLParams:[targetURL query]];
NSString *ref = [targetParams valueForKey:#"ref"];
// Check for the ref parameter to check if this is one of
// our incoming news feed link, otherwise it can be an
// an attribution link
if ([ref isEqualToString:#"notif"]) {
// Get the request id
NSString *requestIDParam = [targetParams
objectForKey:#"request_ids"];
NSArray *requestIDs = [requestIDParam
componentsSeparatedByString:#","];
// Get the request data from a Graph API call to the
// request id endpoint
[self notificationGet:[requestIDs objectAtIndex:0]];
}
}
// Clean out to avoid duplicate calls
self.openedURL = nil;
}
}
Is there any way that these problems are caused by the way that the app is not published on Appstore (Appstore id is not set neither for iPhone nor iPad)?
Here are code snippets showing using of the fb api:
Thank you very much for the time.
Enable deep linking in Facebook app settings
Facebook sdk 3.5 requests not working
I think this link will help you,configure App on Facebook as well

Resources