Facebook API not calling delegate(request) methods if device having Facebook App - iphone

In my app am using Facebook api and in my device am having Facebook app(FBApp) also.
In my app i provided a button to login when we click on button it is opening FBApp login screen and after that it is coming to my app.
Here the following methods are not firing
-(void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response
-(void)request:(FBRequest *)request didLoad:(id)result
This is the button action
- (IBAction)LoginOrLogout
{
// If the user is not connected (logged in) then connect. Otherwise logout.
if (!isConnected)
{
[messageTextField setHidden:NO];
[facebook authorize:permissions];
// Change the lblUser label's message.
**[lblUser setText:#"Please wait..."];** //struck here only not firing delegate response methods above
}
else
{
[facebook logout:self];
[messageTextField setHidden:YES];
[lblUser setText:#"Tap on the Login to connect to Facebook"];
}
isConnected = !isConnected;
[self setLoginButtonImage];
}
Without FBApp it is calling delegate methods successfully.How can we solve this.
Any one can help or suggest.

Actually when you tap on authorize then it will open safari or if there is facebook app on device then it will open facebook app otherwise it will open facebook in safari. If you don't want to open the safari and facebook app then in facebook.m change this statement everywhere where it is calling to NO.
[self authorizeWithFBAppAuth:NO safariAuth:NO];

I was only able to receive those notifications on the AppDelegate class. I tried to create an util class that could be plugged in every project so it could help people using the Facebook API. The problem is that even tho I set the delegate to my util class, the delegate's methods were never called. Try to put then on the AppDelegate..

Related

Google + iPhone API sign in and share without leaving app

I recently integrated the Google + API in my App, it was a breeze, my only problem with it, is that everything requires you to leave the app and then come back (it uses URL schemes for this). This is not the behavior I would like, is there a way to directly call their services and do whatever I want with the responses just like in LinkedIn API?.
I really want to avoid going back and forth between safari and my app. Any suggestions/documentation is appreciated.
Thank you,
Oscar
UPDATE FROM GOOGLE
today, we released a new Google Sign In iOS SDK with full built-in
support for Sign In via WebView:
developers.google.com/identity/sign-in/ios The SDK supports dispatch
to any of a number of Google apps handling Sign In when present, with
WebView fallback after. In all cases, the Safari switch is avoided,
which we've seen to be the key element in avoiding app rejection.
We're looking forward to getting feedback from people using the new
SDK, and hope its use can replace the (ingenious and diligent)
workarounds people have implemented in the meantime.
THE METHOD BELLOW IS NO LONGER NEEDED
THIS METHOD HANDLES THE LOGIN INTERNAL WITH A CUSTOM UIWebView
THIS WORKS AND WAS APPROVED BY APPLE
My app got kicked from review cause of this
"The app opens a web page in mobile Safari for logging in to Google plus,
then returns the user to the app. The user should be able log in without opening
Safari first."
See this link https://code.google.com/p/google-plus-platform/issues/detail?id=900
I did solved it by following steps
1) create a subclass of UIApplication, which overrides openURL:
.h
#import <UIKit/UIKit.h>
#define ApplicationOpenGoogleAuthNotification #"ApplicationOpenGoogleAuthNotification"
#interface Application : UIApplication
#end
.m
#import "Application.h"
#implementation Application
- (BOOL)openURL:(NSURL*)url {
if ([[url absoluteString] hasPrefix:#"googlechrome-x-callback:"]) {
return NO;
} else if ([[url absoluteString] hasPrefix:#"https://accounts.google.com/o/oauth2/auth"]) {
[[NSNotificationCenter defaultCenter] postNotificationName:ApplicationOpenGoogleAuthNotification object:url];
return NO;
}
return [super openURL:url];
}
#end
this will basically prevent anything to be opened from Chrome on iOS
we catch the auth call and redirect it to our internal UIWebView
2) to info.plist, add the Principal class, and for it Application (or whatever you named the class)
Add plist key "NSPrincipalClass" and as the value the class of your main application (class which extends UIApplication, in this case Application (see code above))
3) catch the notification and open an internal webview
When your custom Application class sends ApplicationOpenGoogleAuthNotification, listen for it somewhere (in the AppDelegate maybe) and when you catch this notification, open a UIWebView (use the URL passed by the notification as the url for the webview) (in my case the LoginViewController listens for this notification and when received, it opens a view controller containing only a webview hooked up to delegate)
4) inside the webview
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if ([[[request URL] absoluteString] hasPrefix:#"com.XXX.XXX:/oauth2callback"]) {
[GPPURLHandler handleURL:url sourceApplication:#"com.google.chrome.ios"n annotation:nil];
// Looks like we did log in (onhand of the url), we are logged in, the Google APi handles the rest
[self.navigationController popViewControllerAnimated:YES];
return NO;
}
return YES;
}
or simmilar code, that handles the response
com.XXX.XXX:/oauth2callback from code above, replace with your company and app identifier, like "com.company.appname:/oauth2callback"
you might want to use #"com.apple.mobilesafari" as sourceApplication parameter
So, it depends what you want to do.
Sign-In: this will always call out to another application. If the Google+ application is installed it will call out to that, else it will fall back to Chrome and Safari.
Sharing/Interactive Posts: right now this always uses Chrome or Mobile Safari.
Retrieving friends, writing app activities, retrieving profile information: All this is done with the access token retrieved after sign in, so does not require leaving the application.
It is possible, though rather unsupported, to skip the SDK and pop up a UIWebView, construct the OAuth link dynamically and send the user to that (take a look at GTMOAuth2ViewControllerTouch in the open source libraries that ship with the SDK). Below is the a very rough example of the kind of thing you could do to plumb it back into the GPPSignIn instance.
However, you would be guaranteeing that the user has to enter their username and password (and maybe 2nd factor). With the Google+ app you're pretty much guaranteed to be already signed in, and with the Chrome/Safari route, there is a chance the user is already signed in (particularly if they're using other apps with Google+ Sign-In).
This also doesn't address sharing, so I would strongly recommend using the existing SDK as far as possible. Filing a feature request for the way you would prefer it to work would be a good thing to do as well: https://code.google.com/p/google-plus-platform/issues/list
#interface ViewController() {
GTMOAuth2ViewControllerTouch *controller;
}
#end;
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
GPPSignIn *signIn = [GPPSignIn sharedInstance];
signIn.clientID = #""; // YOUR CLIENT ID HERE.
signIn.delegate = self;
}
- (IBAction)didTapSignIn:(id)sender {
void (^handler)(id, id, id) =
^(GTMOAuth2ViewControllerTouch *viewController,
GTMOAuth2Authentication *auth,
NSError *error) {
[self dismissViewControllerAnimated:YES completion:^{
[controller release];
}];
if (error) {
NSLog(#"%#", error);
return;
} else {
BOOL signedIn = [[GPPSignIn sharedInstance] trySilentAuthentication];
if(!signedIn) {
NSLog(#"Sign In failed");
}
}
};
controller = [[GTMOAuth2ViewControllerTouch
controllerWithScope:kGTLAuthScopePlusLogin
clientID:[GPPSignIn sharedInstance].clientID
clientSecret:nil
keychainItemName:[GPPSignIn sharedInstance].keychainName
completionHandler:handler] retain];
[self presentViewController:controller animated:YES completion:nil];
}
- (void)finishedWithAuth:(GTMOAuth2Authentication *)auth
error:(NSError *)error {
if (!error) {
UIAlertView * al = [[UIAlertView alloc] initWithTitle:#"Authorised"
message:#"Authorised!"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[al show];
[al release];
}
}
The only real trick to this code is that it uses the [GPPSignIn sharedInstance].keychainName - this means that the auth tokens get stored in the same keychain entry as the GPPSignIn button would, which in turn means we can use [[GPPSignIn sharedInstance] trySilentAuthentication] once it has been populated, and keep the same callback based flow as the main library.
#PeterLapisu approach works good if the Google Plus App is not installed.
Then outgoing url prefixes from app are as follows:
#"googlechrome-x-callback:"
#"https://accounts.google.com/o/oauth2/auth"
However if the Google App is installed there is one more outgoing url and the prefix list looks as follows:
#"com.google.gppconsent.2.4.1:"
#"googlechrome-x-callback:"
#"https://accounts.google.com/o/oauth2/auth"
So, if the Google App is installed, it will be launched simultaneously with our app UIViewController that contains webview.Then if user sucessfully logs in with Google App he will be directed back to our app and the ViewController will be visible.
To prevent this Google App should be allowed to login user and direct him back to our app. According to this discussion: https://code.google.com/p/google-plus-platform/issues/detail?id=900 it is allowed by Apple.
So in my implementation firstly I am checking if the Google App is installed:
- (BOOL)openURL:(NSURL*)url {
NSURL *googlePlusURL = [[NSURL alloc] initWithString:#"gplus://plus.google.com/"];
BOOL hasGPPlusAppInstalled = [[UIApplication sharedApplication] canOpenURL:googlePlusURL];
if(!hasGPPlusAppInstalled)
{
if ([[url absoluteString] hasPrefix:#"googlechrome-x-callback:"]) {
return NO;
} else if ([[url absoluteString] hasPrefix:#"https://accounts.google.com/o/oauth2/auth"]) {
[[NSNotificationCenter defaultCenter] postNotificationName:ApplicationOpenGoogleAuthNotification object:url];
return NO;
}
}
return [super openURL:url];
}
EDIT:
Now I can confirm that my app was finally approved with this solution.
I hope it will help somebody.
It merges Google+ and Gmail samples and completely avoids using Google SignIn Button, i.e you do not leave the app.
Add both Google+ and Gmail API to you Google project, in your app login to google as you would to gmail using GTMOAuth2ViewControllerTouch.xib from OAuth2 and set scope to Google+:
-(IBAction)dologin{
NSString *scope = kGTLAuthScopePlusLogin;//Google+ scope
GTMOAuth2Authentication * auth = [GTMOAuth2ViewControllerTouch
authForGoogleFromKeychainForName:kKeychainItemName
clientID:kClientID
clientSecret:kClientSecret];
if ([auth refreshToken] == nil) {
GTMOAuth2ViewControllerTouch *authController;
authController = [[GTMOAuth2ViewControllerTouch alloc]
initWithScope:scope
clientID:kClientID
clientSecret:kClientSecret
keychainItemName:kKeychainItemName
delegate:self
finishedSelector:#selector(viewController:finishedWithAuth:error:)];
[[self navigationController] pushViewController:authController animated:YES];
}else{
[auth beginTokenFetchWithDelegate:self didFinishSelector:#selector(auth:finishedRefreshWithFetcher:error:)];
}
}
and RETAIN the authentication object if signed in successfully, then use that auth object when using google plus services:
GTLServicePlus* plusService = [[[GTLServicePlus alloc] init] autorelease];
[plusService setAuthorizer:self.auth];//!!!here use our authentication object!!!
No need for GPPSignIn.
Full write up is here: Here is Another Solution
Use the (new) Google Sign In iOS SDK.
The SDK natively supports Sign In through WebView when no Google app is present to complete the Sign In process. It also supports potential dispatch to several Google apps for this purpose.

Facebook login fails in UIWebView

In my app I have to load a web page in UIWebView where user can login with Facebook. The problem is that when user clicks login, blank page appears.
Is it possible to get back to first page and be logged in?
Web page works perfectly in Safari and opens new window and after login it closes it and gets back to where it left.
EDIT: wrong URL was provided to UIWebView
I think the sample of facebook SDK for iOS does the log in way you want.
Please refer to the link:
facebook-iOS-SDK-sample: https://github.com/facebook/facebook-ios-sdk/tree/master/sample/Hackbook
Especially this part in https://github.com/facebook/facebook-ios-sdk/blob/master/sample/Hackbook/Hackbook/RootViewController.m
/**
* Show the authorization dialog.
*/
- (void)login {
HackbookAppDelegate *delegate = (HackbookAppDelegate *)[[UIApplication sharedApplication] delegate];
if (![[delegate facebook] isSessionValid]) {
[[delegate facebook] authorize:permissions];
} else {
[self showLoggedIn];
}
}
When you click on log in button, it will open a login dialog, and ask for permission. This is what it looks like: https://developers.facebook.com/docs/mobile/screenshots/ios/#iphone-native
I think the best way to implement the "facebook-related" app is to start with the Hacbook. It is really a nice and detailed sample.
If you want to reload a specific url after the facebook login popup is closed to prevent being stuck on a blank page you can use this code.
First include the UIWebViewDelegate and set your delegate somewhere in your code.
[yourwebView setDelegate:self];
Then use the shouldStartLoadWithRequest method to check request url for close_popup.php which is used by Facebook to close their popup.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSString *urlString = [NSString stringWithFormat:#"%#", request];
if ([urlString rangeOfString:#"close_popup.php"].location == NSNotFound) {
//The close_pop.php is not found. (Do nothing)
} else {
//Facebook closed the popup so we should load the page we now want the user to see.
NSURL*url=[NSURL URLWithString:#"http://www.example.ca/thepageyouwanttoreload.html"];
NSURLRequest*request=[NSURLRequest requestWithURL:url];
[webView loadRequest:request];
}
return YES;
}
SSL issue? As per Joanne use the facebook SDK and you get loads of extra functionality for free, including logging in via the facebook native app if its installed.

Appying our own action to Facebook Login button & closing all Facebook screens.

I am using fbconnect api in my project. When the login dialog gets opened where we entered our credentials, when we click on login button then it is redirected to the publish page how can we close the login page or post to wall page or view.
My problem is I don't want to open any page belongs to face book API, instead i want to open my own page. Any one can help or suggest.
In FBConnect there is a class FBDialog which is using UIWebView for Facebook login authentication. The FBDialog class implements the UIWebView delegate protocol. So if you want to perform your action on login button press then you can handle it in FBDialog.m in UIWebView delegate -
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType
which will call when you press on login button.
You can open your own view depending upon your requirement. After successful Login following delegate method is called
- (void)session:(FBSession*)session didLogin:(FBUID)uid
{
self.usession=session;
[self postToWall];
}
Here i am calling my own custom method postToWall. Where i create publish dialog as below:
-(void)postToWall
{
FBStreamDialog *dialog=[[[FBStreamDialog alloc]init]autorelease];
dialog.userMessagePrompt=#"Enter Message to Post";
[dialog show];
}
You can create your own view in postToWall in place of FBStreamDialog OR if you want to load request of another page then load that URL in Web View of FBStreamDialog.m class.

xcode iphone found cause of problem but don't know fix - ad the launching app store

I have this code in place:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if ( [request.mainDocumentURL.relativePath isEqualToString:#"/upload"] ) {
viewController.view.hidden = NO;
[viewController pushPick:nil];
return NO;
}
return YES;
}
It is supposed to intercept a webview request when the location called is equal to "/upload", it works, however when other requests are made such as a URL to launch the app store it does not work. When I remove this code the admob ad launches the app store fine, but with this code it does not. Something with the "return YES" is not continuing the request to the app store launch. How can I fix this?
A UIWebView never opens the App Store on its own. You're probably overriding a different implementation of that delegate method that handles opening the App Store, so instead of returning YES, you should call the superclass.

iPhone Facebook Connect logout crash after changing views

I've implemented Facebook Connect in my app just like the sample app that Facebook provides and it works well. After a user chooses to share data via Facebook they are taken to a new view and presented with the FB login dialog. When the user is done they exit the FB sharing view and return to my app's previous view. The user stays logged in as long as they don't logout - even if they exit the FB sharing view. This is good and as expected.
I'm using the same viewDidLoad method as the sample SessionViewController.m, and this is where _session is initialized:
- (void)viewDidLoad {
[_session resume];
_loginButton.style = FBLoginButtonStyleWide;
}
However I noticed that if the user presses the Logout button after exiting and re-loading the FB sharing view it will throw SIGABRT or EXC_BAD_ACCESS and crash the app. The EXC_BAD_ACCESS error occurs at the [dialog show] line of the Login button's touchUpInside method:
- (void)touchUpInside {
if (_session.isConnected) {
[_session logout];
} else {
FBLoginDialog* dialog = [[[FBLoginDialog alloc] initWithSession:_session] autorelease];
[dialog show];
}
Even though the user is connected the touchUpInside method is seeing a disconnected session... Sometimes instead of crashing after pressing the Logout button the logout will be successful but the view's status text remains "Logged in as ..." and the set status/upload image buttons are not hidden. Trying to log in again throws a SIGABRT, which looks due to a nil _session.sessionKey in FBRequest.m:344:
[_params setObject:_session.sessionKey forKey:#"session_key"];
Is there something I should be retaining or doing differently across view changes?
EDIT: I found another user having this same issue on the Facebook Developer Forums:
http://forum.developers.facebook.com/viewtopic.php?pid=193727#p193727
There is no solution posted but if I find one I'll update this question.
_session is nil at that point, right (that's consistent with the "always showing not connected"). Where do you initialize _session?
ETA: This is your code, which is taking the place of SessionViewController provided by Facebook Connect, right?
I can't figure out how _session could have been released, but that's what it seems like.
Adding:
You might want to change your button handler to
[_session resume];
and then do whatever you need to do in the didLogin delegate handler. That way the _session instantiates the FBLoginDialog for you.