ios Facebook integration error when logged out and logged in - ios

I am trying to use Facebook integration into my app. I use the following code to log in.
After i am logged in and when i log out the app relaunches completely from the beginning and also each time the permission is asked. I only want it to ask permission in the first time when i login with a particular user. But it asks always when i log out and try to login back with the Facebook button.
- (IBAction)facebook:(id)sender
{
FBLoginView *loginView=[[FBLoginView alloc]init];
loginView.delegate=self;
loginView.readPermissions = #[#"first_name",
#"last_name",
#"location",
#"id",
#"access_token",
#"email"];
NSArray* permissions = [NSArray arrayWithObjects: #"email", nil];
loginView.readPermissions = #[#"email"];
loginView.readPermissions=permissions;
[FBSession openActiveSessionWithAllowLoginUI:YES];
[FBRequestConnection
startForMeWithCompletionHandler:^(FBRequestConnection *connection,
id<FBGraphUser> user1,
NSError *error)
{
if (!error)
{
firstname=user1.first_name;
lastname=user1.last_name;
city=[user1.location objectForKey:#"name"];
email=user1[#"email"];
fbid=user1.id;
Loggedin=#"Y";
[[NSUserDefaults standardUserDefaults]setObject:Loggedin forKey:#"token"];
[[NSUserDefaults standardUserDefaults]synchronize];
}
NSURL *url = [[NSURL alloc]initWithString:[NSString stringWithFormat:#"%#action=currfbuser&email=%#&fb_id=%#",MainURL,email,fbid ]];
NSError *errors;
NSData *data = [NSData dataWithContentsOfURL:url];
NSDictionary *json = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errors];
status = json[#"status"];
user = json[#"user"];
if ([status isEqualToString:#"success"])
{
[self performSegueWithIdentifier: #"LogIN" sender: self];
}
else if (!([fbid isEqualToString:#""]))
{
[self performSegueWithIdentifier: #"Facebooksegue" sender: self];
}
NSLog(#"%#",firstname);
NSLog(#"%#",lastname);
NSLog(#"%#",city);
NSLog(#"%#",email);
NSLog(#"%#",fbid);
}];
}
The following code i have used to log out.
- (IBAction)Logout:(id)sender
{
_DetailsView.hidden=YES;
_fade.hidden=YES;
y=0;
Loggedin=#"N";
user=nil;
NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray* facebookCookies = [cookies cookiesForURL:[NSURL URLWithString:#"http://login.facebook.com"]];
for (NSHTTPCookie* cookie in facebookCookies) {
[cookies deleteCookie:cookie];
}
[FBSession.activeSession closeAndClearTokenInformation];
[[NSUserDefaults standardUserDefaults]setObject:Loggedin forKey:#"token"];
[[NSUserDefaults standardUserDefaults]setObject:user forKey:#"user"];
[[NSUserDefaults standardUserDefaults]synchronize];
[self.navigationController popToRootViewControllerAnimated:YES];
}
This is the first time i am integrating Facebook. So i am not much kind of sure about the code i am using.
The user data fetching is working perfectly fine. The problem is that the app asks for permission each time and if i press Ok or skip for permission both does the same thing that is the app relaunches when i click ok or skip.
The output i obtained has been uploaded in youtube. Please check the following link.
http://youtu.be/ki7BXr8dXmw
I been stuck with this and can't move forward coz of this bug.
Please help me with this and i can give out 50 bounty for the solution when the bounty is available.
Thank you.

Well i have few suggestions. Here you are always opening FB session with login UI.
[FBSession openActiveSessionWithAllowLoginUI:YES];
That is not required always. Once you authorized the user and you got the required permission you no longer needed the login UI. So how will you decide my user is authorized or not?? Just try to login on behalf of user without Login UI (fallback login)
[FBSession openActiveSessionWithAllowLoginUI:NO]; // Should go in viewDidLoad or applicationDidFinishLaunching
If this login attempt success(Taking the cached token), well you have an active FBSession. Now the actual facebook api usage comes. Do a simple check
if (FBSession.activeSession.isOpen)
{
[self getFacebookFriends];
}
else
{
// User is not logged in
[FBSession openActiveSessionWithAllowLoginUI:YES];
}

Related

parse 'pfloginviewcontroller' certain facebook permissions not working in ios

My facebook login with parse is working perfectly with no issues but the access token that is generated is not showing permission for friendlist although I gave that permission at the time of login. I came to know when I used facebook Graph API 'Friendlists'(fbID/friendlists) and the response array is empty. So, also run Graph API explorer with the same access token generated. It does not show me any error and data array is same empty and a debug message with
"The field 'friendlists' is only accessible on the User object after the user grants the 'read_custom_friendlists' permission"
This is the method I am using
WLLoginViewController *login = [[WLLoginViewController alloc]init];
login.fields = PFLogInFieldsFacebook;
NSArray *permission = [[NSArray alloc]initWithObjects:#"email",#"read_custom_friendlists",#"publish_actions",#"user_location",#"user_hometown",#"user_website",#"user_about_me",#"user_photos",#"user_friends",#"read_custom_friendlists", nil];
login.facebookPermissions = permission;
WLLoginViewController has inherited PFUserLoginManager and I am calling it from some other class.
- (void)logInViewController:(PFLogInViewController *)logInController didLogInUser:(PFUser *)user {
[FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
NSLog(#"permissions%#",logInController.facebookPermissions);
if(result) {
if ([result valueForKey:#"hometown"]) {
NSString *nn = [[result valueForKey:#"hometown"] valueForKey:#"name"];
[user setValue:[[result valueForKey:#"hometown"] valueForKey:#"name"] forKey:#"hometown"];
}
if ([result valueForKey:#"location"]) {
[user setValue:[[result valueForKey:#"location"] valueForKey:#"name"] forKey:#"location"];
}
[user setObject:[result valueForKey:#"id"] forKey:kWLUser_FacebookId];
[user setObject:[result valueForKey:#"name"] forKey:kWLUser_Name];
[user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if([PFInstallation currentInstallation]) {
// save in background current installation.
[[PFInstallation currentInstallation] setObject:user forKey:#"user"];
[[PFInstallation currentInstallation]saveInBackground];
}
}];
[[ParseManager sharedInstance]saveDeviceToken:[[NSUserDefaults standardUserDefaults]objectForKey:#"DeviceToken"]];
[self dismissViewControllerAnimated:YES completion:nil];
}else {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Could not login" message:#"Could not login to facebook, please try again" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
}];
}
This is the method which is which is running when the user return to the app from facebook.The nslog in the code is showing the permission perfectly which I gave.
And finally this is the method for handling facebook request
-(void)handleFacebookFriendsRequest {
NSString *queryParams = #"id,name,picture.width(350).height(250),location,hometown,likes.limit(100000),statuses.limit(1),languages";
[queryParams stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%#",[FBSession activeSession].permissions);
NSLog(#"%#",[[FBSession activeSession].permissions description]);
NSLog(#"%#",[FBSession activeSession].accessTokenData.accessToken);
[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:#"me/friends?fields=%#",queryParams] completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
//change For getting everything out
NSLog(#"%#",[result objectForKey:#"data"]);
[[ApplicationDataModel sharedInstance]setFacebookFriendsList:[result objectForKey:#"data"]];
[self facebookRequestDidLoad:result];
} else {
[self facebookRequestDidFailWithError:error];
}
}];
}
I am stuck badly need help. Thanks in advance
The read_custom_friendlists is not a default permission, as a result you have to go through the approval process for this feature (https://developers.facebook.com/docs/facebook-login/permissions/v2.2)
To submit items for approval go to:
developers.facebook.com -> My Apps -> Status & Review
Caveat: "People listed in the Roles section of your App Dashboard - including Admins, Developers and Testers - can grant any permission without review. If only people in these Roles will use your app, you don't need to submit it for Login Review."(https://developers.facebook.com/docs/apps/faq)

Logout of Active Twitter Session Using Fabric

I have read through the forums and suggestions about how to logout of Twitter in Xcode for IOS using Fabric, but I can't get the logOut method to call and logout the user from the current session. Here is my current code for the login view controller:
- (IBAction)TESTT:(id)sender {
[[Twitter sharedInstance] logInWithCompletion:^
(TWTRSession *session, NSError *error) {
if (session != nil) {
NSLog(#"signed in as %#", [session userName]);
} else {
NSLog(#"error: %#", [error localizedDescription]);
}
}];
}
- (IBAction)LOGOUT:(id)sender {
[self logOut];
}
- (void)logOut{
[[Twitter sharedInstance] logOut];
}
I have imported and have the login functionality working well from the Fabric tutorial.
I just can't get the button that I made which is using the LOGOUT action to logout the user from the current Twitter session. I have even tried to clear the cookies to see if that could wipe the Twitter session from the memory and reset it - but nothing. If anyone could help me out I would really appreciate it - thanks!
FYI: PLEASE do not suggest only [[Twitter sharedInstance] logOut]; . This method does not do what I am asking by itself. If someone can tell me how to successfully logout using this method along with the rest of the procedure that would be fine.
After a long extensive series of methods, clearing of cookies, data, almost everything you could think of, I discovered it is actually quite simple.
The easiest way to sign out and clear the previous user session is as follows:
Go to settings
Go to your Twitter and Disallow Twitter access to your app (it should appear here)
Go back to the app and call the following method:
- (void)twitterLogout:(id)sender {
NSUserDefaults *twitterSession = [NSUserDefaults standardUserDefaults];
[twitterSession setObject:0 forKey:#"TwitterSession"];
[twitterSession synchronize];
NSLog(#"Twitter session = %#", twitterSession);
[[Twitter sharedInstance] logOut];
[self.view insertSubview:_logoutTwitter atIndex:16];
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies])
{
NSString* domainName = [cookie domain];
NSRange domainRange = [domainName rangeOfString:#"Twitter"];
if(domainRange.length > 0)
{
[storage deleteCookie:cookie];
}
}
NSURL *url = [NSURL URLWithString:#"https://api.twitter.com"];
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url];
for (NSHTTPCookie *cookie in cookies)
{
[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}
}
There is quite a lot in this method, and to be honest some of it is probably extraneous and not even needed, but anyone who needs this can mess around with what should and shouldn't stay. Either way hopefully this helps people - it certainly helped me!
You can use this simple code for Swift 3:
let store = Twitter.sharedInstance().sessionStore
if let userID = store.session()?.userID {
store.logOutUserID(userID)
}

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.

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

Login Logout issue with facebook iOS sdk

We have got sruck in the iOS facebook login logout issue. When I login to facebook using my application it will prompt for user permission with 'login' and 'cancel' button. But this screen appears only on the very first time. ie Once we logged in using safari or the app and even if we logged out from facebook , application the screen prompting for user permission displays only an 'ok' button. It doesnt allow to sign in as a different user. Why the screen with 'login' and 'cancel' button not displaying each time the application launches? I tried by deleting cookies and removing NSUserDefaults but no luck.
The problem is after logout, I am unable to login to the facebook as another user. It still shows as the same user.
I am calling the below logout function in sdk
(void)logout:(id<FBSessionDelegate>)delegate {
self.sessionDelegate = delegate;
[_accessToken release];
_accessToken = nil;
[_expirationDate release];
_expirationDate = nil;
NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray* facebookCookies = [cookies cookiesForURL:
[NSURL URLWithString:#"http://login.facebook.com"]];
for (NSHTTPCookie* cookie in facebookCookies) {
[cookies deleteCookie:cookie];
}
if ([self.sessionDelegate respondsToSelector:#selector(fbDidLogout)]) {
[_sessionDelegate fbDidLogout];
}
}
Also in fbDidLogout delegate function I removed all NSUserDefaults objects
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"FBAccessTokenKey"]) {
[defaults removeObjectForKey:#"FBAccessTokenKey"];
[defaults removeObjectForKey:#"FBExpirationDateKey"];
[defaults synchronize];
}
regrds
Shihab
You can clear the session as well as clearing the cookies with the following code:
FBSession* session = [FBSession activeSession];
[session closeAndClearTokenInformation];
[session close];
[FBSession setActiveSession:nil];
NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray* facebookCookies = [cookies cookiesForURL:[NSURL URLWithString:#"https://facebook.com/"]];
for (NSHTTPCookie* cookie in facebookCookies) {
[cookies deleteCookie:cookie];
}
FBSession openWithBehavior:completionHandler: can be used..
FBSession *fbSession = [[FBSession alloc] initWithPermissions:[NSArray arrayWithObjects:#"email",#"publish_actions",#"publish_stream", nil]];
[fbSession openWithBehavior:FBSessionLoginBehaviorForcingWebView completionHandler:^(FBSession *session,FBSessionState state, NSError *error){
[FBSession setActiveSession:fbSession]; // Retain the Active Session.
}];
For Logging out, Ans by Ellen S.. worked fine for iOS .
I modified fbDidLogout method and it worked, here is the code:
-(void) fbDidLogout
{
NSLog(#"Logged out of facebook");
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies])
{
NSString* domainName = [cookie domain];
NSRange domainRange = [domainName rangeOfString:#"facebook"];
if(domainRange.length > 0)
{
[storage deleteCookie:cookie];
}
}
}//End of Method
The method successfully logs out the user.
Hope this will help!
I just figure it out I got in the settings of my iPhone and got to privacy chose the Facebook tab and turn off where it says Applications that have requested access to you Facebook account will appear here. It works!!!
When login to set to loginBehavior, so when you exit, with the other account login, won't appear only authorized, without the login screen login.loginBehavior =FBSDKLoginBehaviorWeb; i use facebook 4.11,it's work

Resources