I have a standard implementation of the Single Sign On for iOS with the AppDelegate listening for the handleOpenURL. Prior to today, this implementation was working fine. I have made no changes to the implementation today, yet the redirect from Facebook in Safari ( on the Simulator ) and the redirect from Facebook app ( on the actual device ) no longer return any data to my app.
I am forwarded to login without issue and login successfully to see that I have already authorized the current app and can now click "Okay", which I do. When the app returns to focus ( after Facebook redirects back to it ), there is no data returned with the redirect.
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
NSLog(#"url recieved: %#", url);
NSLog(#"query string: %#", [url query]);
NSLog(#"host: %#", [url host]);
NSLog(#"url path: %#", [url path]);
// from facebook login
if ( [[url scheme] isEqualToString:FACEBOOK_URL_SCHEME] ) {
return [SESSION.facebook handleOpenURL:url];
}
return YES;
}
The values for all of the logs are empty - the app logs nothing. The request to authorize is below:
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"publish_actions",
#"email",
#"user_checkins",
#"user_likes",
#"user_photos",
#"offline_access",
#"publish_stream",
#"read_friendlists",
nil];
[SESSION.facebook authorize:permissions];
Again, this very code worked perfectly yesterday and for the last 3 weeks. Today it simply stopped working. Any help is appreciated. Please let me know if more code is needed to evaluate the issue.
Thanks in advance!
Jane
Now - for no explainable reason it is working again. I did check Facebook SDK Status prior to posting here and everything was green. I guess I'll chalk this one up to a blip in the internets.
I'm using FBConnect sdk in order to publish posts to a user's profile via my application. I'm having a number of problems with this:
When the relevant code runs for the first time on the device, the user is re-directed, as wanted, to the facebook app/website, which asks him to authorize it. if the user authorizes it, it returns back to the application, which pops a "Connect to facebook" view controller which asks the user to log in. this is weird, as the user is already logged in, otherwise how could he authorize the app? but I guess this may be ok, as he hadn't logged in through the app yet. after he logs in, it does nothing. only the second time the code gets run, after he authorized the app, the user gets the posting dialog.
If the user hadn't authorized the app, when it comes back to my app after the authorization dialog, it asks the user to login ( just as if he authorized ), and does nothing after he had logged in. only the second time the code gets ran, the authorization dialog opens, with the optinos "Authorize" & "Leave App", instead of "Authorize" & "Don't authorize" / "Allow" & "Don't Allow".
In addition, if the user has deleted his authorization via his account's settings on facebook, instead of just asking him to re-authorize it, a facebook dialog pops ( instead of the post/authorization dialog ), saying: "An error occurred. Please try again later." Trying later doesn't help. it will pop always, even if u restart the app. the only way to make it go away is to re-install the app, which will cause it to re-pop the authoriziation dialog.
So here's what I want to achieve:
After the user authorizes the app, he wouldn't have to log in again.
After the user authorizes the app, the posting dialog will pop immedietly, without him having to re-run the code ( which is triggered, btw, with a button ).
If the user un-authorizes the app, he will be prompted again with the authorization dialog, instead of the error dialog
If he refused the authorization, I will call a function that displays an error/etc.
Here's the relevant code:
MyViewController.m
- (void)shareOnFacebook
{
Facebook *facebook = [[Facebook alloc] initWithAppId:myAppID];
[(MyAppDelegate *)[[UIApplication sharedApplication] delegate] setFacebook:facebook];
[facebook release];
facebook = [(MyAppDelegate *)[[UIApplication sharedApplication] delegate] facebook];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"FBAccessTokenKey"] && [defaults objectForKey:#"FBExpirationDateKey"]) {
facebook.accessToken = [defaults objectForKey:#"FBAccessTokenKey"];
facebook.expirationDate = [defaults objectForKey:#"FBExpirationDateKey"];
}
if (![facebook isSessionValid]) {
[facebook authorize:[NSArray arrayWithObjects:#"publish_stream", nil] delegate:(MyAppDelegate *)[[UIApplication sharedApplication] delegate]];
}
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
//Giving the dictionary some parameters for posting defaults
[facebook dialog:#"feed" andParams:dictionary andDelegate:self]; //Note: we have 2 different delegates! appDelegate for connections & url switching, and self for dialogs
}
MyAppDelegate.h
#interface MyAppDelegate : NSObject <UIApplicationDelegate, FBSessionDelegate, FBDialogDelegate>
{
Facebook *facebook; // kept for facebook sharing, accessed only from MyViewController although delegate methods are handeled in here
}
#property (nonatomic, retain) Facebook *facebook;
#end
MyAppDelegate.m
- (void)fbDidLogin
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[facebook accessToken] forKey:#"FBAccessTokenKey"];
[defaults setObject:[facebook expirationDate] forKey:#"FBExpirationDateKey"];
[defaults synchronize];
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
return [self.facebook handleOpenURL:url];
}
Is it possible that I'm missing a couple of delegate functions on MyViewController? Because I see for some reason I've marked it as implementing the FBDialogDelegate protocol, although he doesn't implement any function from there.
I'd be really glad if you guys would help me, as this is extremely frustrating for me. I couldn't find nothing about this on the internet, and I feel like im drowning in here.Tnx in advance!
First:
[facebook authorize:[NSArray arrayWithObjects:#"publish_stream",#"offline_access",nil] delegate:self];
The offline_access key here will keep your auth token alive forever (or, more specifically, until the user manually de-authorizes your application in their application settings in their Facebook account settings). Also, set your active VC as the delegate (more on that later).
Secondly:
-(void)popUserShareFeed {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
//Giving the dictionary some parameters for posting defaults
[facebook dialog:#"feed" andParams:dictionary andDelegate:self];
}
Call this method (or one like it) in your -fbDidLogin delegate method. Also call it in your original method if the session was still valid, i.e.:
if (![facebook isSessionValid]) {
[facebook authorize:[NSArray arrayWithObjects:#"publish_stream", nil] delegate:(MyAppDelegate *)[[UIApplication sharedApplication] delegate]];
} else {
[self popUserShareFeed];
}
...and your new fbDidLogin:
- (void)fbDidLogin
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[facebook accessToken] forKey:#"FBAccessTokenKey"];
[defaults setObject:[facebook expirationDate] forKey:#"FBExpirationDateKey"];
[defaults synchronize];
[self popUserShareFeed];
}
(Note: you'll have to define this in MyViewController.m and use it as your FBSessionDelegate. It will be functionally equivalent. Your AppDelegate does not need to also be your FBSessionDelegate.
Third:
Implement the -fbDidNotLogin:(BOOL)cancelled FBSessionDelegate method, like so:
-(void)fbDidNotLogin:(BOOL)cancelled {
if (cancelled) {
... some alert about the user cancelling...
} else {
... some alert about how it failed for some reason...
}
}
Fourth, as far as your bizarro errors go: A) the Facebook SDKs in general are not great, and B) I'd only set the auth token and the expiration date on your facebook object if
A) you don't already have one instantiated (i.e., it's nil)
and
B) the expirationDate you're setting is in the future (i.e. timeIntervalSinceNow [the NSDate instance method] called on it returns > 0).
Sounds like you're experiencing the same issue described in this Facebook Platform Developer forum post. I'm encountering the same problem, but on the web. Only one response was given from Facebook in that thread, and it's wrong information.
Facebook has the worst developer docs and developer support ever, I wouldn't hold my breath waiting on a solution.
I had similar but not the same problem: message "An error occurred. Please try again later." was shown always.
The problem was with not properly configured App ID - it was provided by customer (so I'm not sure what exactly was wrong); everything works properly since I replaced it with my own test App ID (from previous app).
I have integrated FBConnect in so many applications , but never face such kind of critical issue. So, there would be something missing in your code:
Insted of checking FBAccessTokenKey & FBExpirationDateKey, simply try with session object of FBSession class of FBConnect.
Just try using mine code with few conidtions:
session = [[FBSession sessionForApplication:#"key" secret:#"AppSecretKey" delegate:self] retain];
[session resume];
_posting = YES;
// If we're not logged in, log in first...
if (![session isConnected]) {
loginDialog = nil;
loginDialog = [[FBLoginDialog alloc] init];
[loginDialog show];
}
// If we have a session and a name, post to the wall!
else if (_facebookName != nil) {
[self postToWall]; // Over here posting dialog will appear , if user has already logged in or session is running.
}
}
else {
[FBBtn setTitle:#"Login" forState:UIControlStateNormal]; // if you want to change the title of button
[session logout];
}
Additionally take care of releasing the session object in dealloc method only , rather than releasing it in any other method.
- (void)dealloc {
[super dealloc];
[session release];
session = nil;
}
Hope that would solve your problem.
Not a direct solution for your code problems, but...
Have you consider using an open-source library for this? ShareKit is a great example: http://getsharekit.com . The integration is dead simple and it does everything you need.
I was having the exact same issue, and used Ben Mosher's response above, but I also decided to create a simple singleton class for the Facebook object, so that in my AppDelegate I can handle the following function properly:
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
return [[[FBManager defaultManager] facebook] handleOpenURL:url];
//return [facebook handleOpenURL:url];
}
My singleton class is both FBSessionDelegate and FBDialogDelegate, so it handles the corresponding methods.
This allows me to only prompt the user to login when they are actually trying to post something, instead of when the app launches.
I Successfully Integrate Facebook in my App.Its also working fine on simulator and Iphone,With the dialog box.
But when i install facebook official App from Itunes in my Iphone.On share function it will take my App resources to that App.with the following pages.And when I delete Facebook Official App.Its again Works fine.
Any Solution???? Thanks in advance
Comment out the following lines of code of function
- (void)authorizeWithFBAppAuth:(BOOL)tryFBAppAuth safariAuth:(BOOL)trySafariAuth
in Facebook.m :
UIDevice *device = [UIDevice currentDevice];
if ([device respondsToSelector:#selector(isMultitaskingSupported)] && [device isMultitaskingSupported]) {
if (tryFBAppAuth) {
NSString *scheme = kFBAppAuthURLScheme;
if (_localAppId) {
scheme = [scheme stringByAppendingString:#"2"];
}
NSString *urlPrefix = [NSString stringWithFormat:#"%#://%#", scheme, kFBAppAuthURLPath];
NSString *fbAppUrl = [FBRequest serializeURL:urlPrefix params:params];
didOpenOtherApp = [[UIApplication sharedApplication] openURL:[NSURL URLWithString:fbAppUrl]];
}
if (trySafariAuth && !didOpenOtherApp) {
NSString *nextUrl = [self getOwnBaseUrl];
[params setValue:nextUrl forKey:#"redirect_uri"];
NSString *fbAppUrl = [FBRequest serializeURL:loginDialogURL params:params];
didOpenOtherApp = [[UIApplication sharedApplication] openURL:[NSURL URLWithString:fbAppUrl]];
}
}
This will always show a dialog box to the user.
I have the following function to post to Facebook using the latest iOS Facebook SDK.
-(void)fbPost:(NSMutableDictionary *) params{
NSLog(#"fbPost called");
if (![facebook isSessionValid]) {
NSLog(#"session invalid, calling fblogin");
[self fblogin];
}
if ([facebook isSessionValid]) {
NSLog(#"session valid, calling publishToFB");
[self.facebook dialog:#"stream.publish" andParams:params andDelegate:self];
}
}
It works fine when there is no existing session: it logs in to facebook, gets permissions, returns to the app, shows the dialog and publishes the status. However, when trying a second time, isSessionValid returns true the first time and nothing happens, although the log shows publishToFB is called.
The session is persisted in fbDidLogin:
[[NSUserDefaults standardUserDefaults] setObject:self.facebook.accessToken forKey:#"AccessToken"];
[[NSUserDefaults standardUserDefaults] setObject:self.facebook.expirationDate forKey:#"ExpirationDate"];
[[NSUserDefaults standardUserDefaults] synchronize];
and loaded in application didFinishLaunchingWithOptions:
facebook.accessToken = [[NSUserDefaults standardUserDefaults] stringForKey:#"AccessToken"];
facebook.expirationDate = (NSDate *) [[NSUserDefaults standardUserDefaults] objectForKey:#"ExpirationDate"];
I made sure to ask for offline_access permission when logging in:
_permissions = [[NSArray arrayWithObjects:
#"publish_stream",#"offline_access",nil] retain];
It appears the problem was in drawing the dialog in this code in FBDialog.m
UIWindow* window = [UIApplication sharedApplication].keyWindow;
if (!window) {
window = [[UIApplication sharedApplication].windows objectAtIndex:0];
}
If I comment out the If clause, it works OK. I guess that in my app setup, "keyWindow" is not front-most, so the dialog was not showing up.
I am new to iphone development, i want to display the permission page after logging facebook.
buttonIndex is the index of my actionsheets.
if(buttonIndex == 1)
{
session = [FBSession sessionForApplication:#"My App key" secret:#"My Key" delegate:self];
FBLoginDialog* dialog = [[[FBLoginDialog alloc] initWithSession:session] autorelease];
[dialog show];
}
by using those code successfully loggin to facebook, but i want to permission page to display,
so i can use,
- (void)session:(FBSession*)session didLogin:(FBUID)uid
{
NSLog(#"User with id %lld logged in.", uid);
FBPermissionDialog* dialog1 = [[[FBPermissionDialog alloc] init] autorelease];
dialog1.delegate = self;
dialog1.permission = #"uid";
[dialog1 show];
}
But its not working. Where can i put that code.
And I want to share my content after the permission allowed.
If i logout the facebook, it goes to the browser but i want to return my application after logout,
Please help me out, guide me plz.
I would change this dialog1.permission = #"uid"; to something like this
dialog1.permission = #"publish_stream";. Because you want to publish your content to the users stream, right?
- (void)session:(FBSession*)session didLogin:(FBUID)uid
After loggin in I would first check if you might already have the permission to publish to the user's stream, by creating a FBRequest
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys: #"publish_stream", #"ext_perm", nil];
[[FBRequest requestWithDelegate:self] call:#"facebook.users.hasAppPermission" params:params];
The result you can evaluate here
- (void)request:(FBRequest*)request didLoad:(id)result
e.g. like this
if ([request.method isEqualToString:#"facebook.users.hasAppPermission"])
{
NSString *success = result;
if ([success isEqualToString:#"1"])
{
NSLog(#"User has app permission");
// publish content now
...
}
else
{ // else ask for permission, opening permission dialog
...
}
I highly recommend this guy's tutorial, Brandon Treb, on integrating Facebook. He does a very thorough presentation and takes you line-by-line, so if it does not work, its a typo on your part. His tutorial got me up and running in less than two hours.
http://brandontreb.com/