Facebook api with Xamarin - facebook

I am creating an application by Xamarin (andoroid / iOS) and would log in using facebook, and I do so by sharing the same access code?

You can do it by following the code sample I've published here: https://github.com/IdoTene/XamarinFormsNativeFacebook
a guide of how to do so:
Steps to set up your project:
Installation:
1) For Android download from nuget/Components the Facebook Android SDK: http://components.xamarin.com/view/facebookandroid and place it in your droid project.
2) For iOS download from nuget/Components the Facebook iOS SDK: http://components.xamarin.com/view/facebookios and place it in your iOS project.
Set up components:
Shared code set up:
1) Add a FacebookLoginButton which inherits from Button, leave it without any implementation
2) Add that button to the login page
3)Add to App.cs the following property:
public static Action<string> PostSuccessFacebookAction { get; set; }
4) in the LoginPage.xaml.cs (or in the viewmodel class if you have one), add the navigation for this action:
App.PostSuccessFacebookAction = async token =>
{
//you can use this token to authenticate to the server here
//call your FacebookLoginService.LoginToServer(token)
//I'll just navigate to a screen that displays the token:
await Navigation.PushAsync(new DiplayTokenPage(token));
};
Android: 1) Add to strings.xml file (found at Resources/Valus) The following lines {Your App Id Here} {Your App Name}
2) Add to Manifest.xml the following code:
3) Create activity class for facebook (I called it FacebookActivity)
4) Create a custom rendrer for the facebook Login button (I called it FacebookLoginButtonRendererAndroid)
5) Add to mainActivity class The OnActionResult method to handle response from the FacebookActivity
iPhone:
1) In AppDelegate class, register in method FinishedLaunching the following:
FBSettings.DefaultAppID = FacebookAppId;
FBSettings.DefaultDisplayName = FacebookAppName;
2) Override the following methods:
public override bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
{
base.OpenUrl(application, url, sourceApplication, annotation);
return FBSession.ActiveSession.HandleOpenURL(url);
}
public override void OnActivated(UIApplication application)
{
base.OnActivated(application);
// We need to properly handle activation of the application with regards to SSO
// (e.g., returning from iOS 6.0 authorization dialog or from fast app switching).
FBSession.ActiveSession.HandleDidBecomeActive();
}
3) Create a custom rendrer for the facebook Login button (I called it FacebookLoginButtonRendererIos)

Related

params for switch to favorites pane (Home Feature not loading favorites)

i have this requirement on IBM Content Navigator about a personalized (feature) homepage with various buttons used to switch between feature; i've made all works except for the one linked to the Home feature (favorites)
i've already tried to call the feature with thoose params:
params.repositoryId="FNOSARCHIVIO";
params.application="navigator";
params.desktop="OneFile";
params.userid="sys.filenetsvil";
but with no success, the feature is switched (after the button press it switch to the home feature) but it does not load the favorites of the user
here is my switch-feature method (taken for the ibm icn redbook + some modification)
switchFeature: function (featureIdToSwitch) {
//get layout from destop
var layout = ecm.model.desktop.getLayout();
// get the corresponding button of the LaunchBar Container
var feaButt = layout.launchBarContainer.getFeatureButtonByID(featureIdToSwitch);
var params = {};
// params.repositoryId="FNOSARCHIVIO";
// params.application="navigator";
// params.desktop="OneFile";
// params.userid="sys.filenetsvil";
// switching to the target feature
// feaButt.child.loadContent;
layout.launchBarContainer.selectContentPane(feaButt, featureIdToSwitch, params);
}
on the frontend i have 4 simple dojo buttons with onClick action, nothing special.
i use this feature id:
switchToHome: function () {
this.switchFeature('favorites');
},
this is what i mean when i say "it switch the feature but do not load the favorites:"
Home feature called from my button:
https://ibb.co/GMW7L2x
Home feature called from the standard toolbar:
https://ibb.co/BBgr36L
looks like it is loading the feature but it is not calling the listFavorites()
i cannot find any help on IBM docs or forum, any help here ? thanks!
At least i managed to do it, i post it here, hope helps someone:
1- override the default favorite feature (the java class), using the same js plugin, overriding this:
#Override
public String getContentClass() {
return "ecm.widget.layout.HomePane";
}
and set it to preLoaded:
#Override
public boolean isPreLoad() {
return true;
}
then, on the frontend, retrive the js feature, and load the content:
var targetFeature = layout.launchBarContainer.getContentPaneByID(featureIdToSwitch);
targetFeature.loadContent()
you can call the loadContent() only if the feature has been preLoaded or alredy invoke at leat once

Share image on Facebook

WP8 how to share data from my app to Facebook
or twitter
i want to take screen-shoot of my list-box and then share it on Facebook
i try this code
ShareLinkTask shareLinkTask = new ShareLinkTask();
shareLinkTask.Title = "Code Samples";
shareLinkTask.LinkUri = new Uri("https://www.facebook.com/", UriKind.Absolute);
shareLinkTask.Message = "Here are some great code samples for Windows Phone.";
shareLinkTask.Show();
but it doesnot work
You should not use ShareLinkTask for sharing photos. You should use ShareMediaTask. You can more information and how to implement ShareMediaTask by clicking link I provided herewith.
Here's the code:
CameraCaptureTask cameraCaptureTask = new CameraCaptureTask();
//declare it globally
cameraCaptureTask.Completed += cameraCaptureTask_Completed;
//declare it in Constructor
cameraCaptureTask.Show();
//declare it in any method.
For example, button click event. By using this method, you can capture the list box.
//declare this method anywhere in the cs page
void cameraCaptureTask_Completed(object sender, PhotoResult e)
{
if(e.TaskResult == TaskResult.OK)
{
ShowShareMediaTask(e.OriginalFileName);
}
}
void ShowShareMediaTask(string path)
{
ShareMediaTask shareMediaTask = new ShareMediaTask();
shareMediaTask.FilePath = path;
shareMediaTask.Show();
}
Now, You can easily take screenshot of app's listbox and share it with any of the social networks where user installed on their phone. Cheers.!

Facebook SDK for Xamarin.iOS login return issue

I'm trying to use the Facebook SDK for Xamarin.iOS(the one from Facebook, not from Octorcurve) to get the users Authed on my app.
I've followed the Sample that comes with the component from the store. The sample just works but I'm stuck after the login/permissions without firing the events to notify the viewController that we have a user logged in. I have set the plist file with the app name, id, and Url schema as requested by facebook SDK. So, the code is:
Note that I'm not creating the UI from code. I have a .xib IB file with the UI and yes, I added a view for the FBLoginView and set its custom class to FBLoginView.
AppDelegate.cs(omitted the rest of code for brevity):
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
// create a new window instance based on the screen size
window = new UIWindow (UIScreen.MainScreen.Bounds);
viewController = new LoginViewController ();
navController = new UINavigationController (viewController);
window.RootViewController = navController;
window.MakeKeyAndVisible ();
return true;
}
public override bool OpenUrl (UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
{
return FBSession.ActiveSession.HandleOpenURL(url);
}
public override void OnActivated (UIApplication application)
{
FBSession.ActiveSession.HandleDidBecomeActive();
}
LoginViewController.cs(the controller for the NIB file):
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
loginView = btnLogin as FBLoginView;
loginView.ReadPermissions = new string[] { "email" };
loginView.PublishPermissions = new string[]{ "publish_actions", "publish_stream", "manage_pages" };
loginView.DefaultAudience = FBSessionDefaultAudience.Everyone;
loginView.ShowingLoggedInUser += (sender, e) =>
{
var a = e;
};
loginView.FetchedUserInfo += (sender, e) =>
{
user = e.User;
};
}
So, whis this code I have 2 issues:
Note that I'm casting btnLogin as FBLoginView since idk how to set the outlet on Interface Builder to use the right type of FBLoginView... It always say that it its type wasnt found when I'm adding the Outlet in the .h file. So I just created it as UIView and did the cast on the code. This cast is valid and still working, since the permissions that I'm passing are being asked for user authorisation at the consent FB screen.
The two events ShowingLoggedInUser and FetchedUserInfo never get called and the AppDelegate never call OpenUrl neither OnActivated.
Am I missing something? All I need is get the access_token that should be returned somewhere after the login. How do I get it?
I really appreciate any help.
Thanks!
Just to provide feedback for people...
Suddenly, after 2 days hitting my head agains the wall, I just cleaned the project, rebuild it and restarted Xamarin STUDIO... Now the events are fired... No single thing changed and things are working...
There are weird behaviours unexplained to me with Xamarin that just work or not, like sometime I start the app, and it just hangs on "Waiting for debugger to connect..." and nothing happens connecting to the device while in Simulator it works fine...
Thanks

Logging out from facebook using facebook c# sdk in WP7

I want to implement logout from facebook using facebook C# sdk in my windows phone app
My primary question is how do we logout using Facebook C# SDK in WP7
I found this article in search
Article link
there he is trying to find the logout url using regex, but that did not working in my app
when i try that the browser navigated event is going into infinite loop
you can share any samples/posts related to facebook logout in windows phone 7.
I want logout should happen with out user intervention, after he clicks on a button he should looged out from facebook and from next time he should see the login page
I tried following posts/blogs also but no use.
LINK 1
LINK 2 this giving error while splitting the accesstoken
UPDATE
LogOutButtonCode
FacebookClient _fbClient = new FacebookClient(fbaccess.AccessToken);
var logoutParams = new Dictionary<string, object>();
logoutParams.Add("next", "https://www.facebook.com/connect/login_success.html");
//logoutParams.Add("",)
var logoutUrl = _fbClient.GetLogoutUrl(logoutParams);
BrowserControl.Navigated += new EventHandler<System.Windows.Navigation.NavigationEventArgs>(BrowserControl_Navigated);
BrowserControl.Navigate(new Uri(logoutUrl.AbsoluteUri));
Navigated Event CODE
if (e.Uri.AbsoluteUri == "https://www.facebook.com/connect/login_success.html")
{
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
e.Uri.AbsoluteUri returns https://www.facebook.com/home.php
Logout URL i am getting from the server https://www.facebook.com/logout.php?next=https://www.facebook.com/connect/login_success.html
Use FacebookClient.Logout to generate the logout url.
This is the snippet from winforms sample which will work in wp7 with some modifications.
private void btnLogout_Click(object sender, EventArgs e)
{
var fb = new FacebookClient();
var logoutUrl = fb.GetLogoutUrl(new
{
next = "https://www.facebook.com/connect/login_success.html",
access_token = _accessToken
});
var webBrowser = new WebBrowser();
webBrowser.Navigated += (o, args) =>
{
if (args.Url.AbsoluteUri == "https://www.facebook.com/connect/login_success.html")
Close();
};
webBrowser.Navigate(logoutUrl.AbsoluteUri);
}
Make sure to persist the access token somewhere when you login as it is required to logout.

Facebook action script 3 API login/logout issue

I'm making mobile AIR app for Android using Flash builder 4.5, AIR 2.6, Facebook action script 3 API the latest version.
I have a problem with login/logout. I can login only one time - then my data caches somehow and Facebook automatically logs me in. When I call logout I receive response TRUE, but I don't really logout from system. Standard login dialog doesn't appear for me. I have already read a lot of articles on stackoverflow and open issues on official site, but none of them were helpfull. How can I solve this? Here is the code I use:
package
{
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.display.Stage;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.external.ExternalInterface;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.system.Capabilities;
import flash.system.Security;
import flash.display.Loader;
import com.facebook.graph.FacebookMobile;
public class TestProj extends Sprite
{
public function TestProj()
{
super();
//register to add to stage
this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
// support autoOrients
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
}
private function onAddedToStage(event:Event):void
{
this.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
FacebookMobile.init("195053007196177", initCallback);
}
private function initCallback(success:Object, fail:Object):void
{
var appPermissions:Array = new Array("read_stream", "offline_access", "publish_stream", "read_friendlists");
FacebookMobile.login(loginCallback, this.stage, appPermissions);
//FacebookMobile.logout(logoutCallback);
}
private function loginCallback(success:Object, fail:Object):void
{
//And here I always receive success with my UserID
//and login dialog don't appears to me before this
if (success)
{
trace("login ok");
}
else
trace("login failed");
}
private function logoutCallback(success:Object):void
{
//here I reseive "TRUE" always!!
trace(success);
}
}
}
You're only passing the 1st argument of logoutCallback to your logout method. If you add in the 2nd argument of your site url specified for your app, it should clear it out the html cookie for that window. Also, set FacebookMobile.manageSession = false;
FacebookMobile.logout(logoutCallback, "http://your_app_origin_url");
There is a potential, related bug that involves Desktop and Mobile not accessing or clearing the access token's the same way. For that, there's a hack that describes exposing the access token in FacebookMobile, then manually calling the "logout" method with the access token. The issue is described here, including a method called "reallyLogout". If what I've written above doesn't work, implement "reallyLogout".
When you log out, your app clears the local session but does not log you out of the system. This is clearly defined in the documentation for logout. Think about it, if you're logged into Facebook on your Smartphone, Web Browser, and now this Mobile Desktop App, and suddenly you log out... it shouldn't log you out EVERYWHERE, just within that browsers session. So pass that 2nd parameter.
I've had this exact problem, and after trying numerous fixes, this finally seems to work:
The default logout functionality seems to not be properly clearing cookies via the FacebookMobile actionscript API. The solution in comment #33 here worked for me, reproduced here. Make sure to sub in your own APP_ID:
function logout(e:MouseEvent):void {
FacebookMobile.logout(onLogout, "https://m.facebook.com/dialog/permissions.request?app_id=APP_ID&display=touch&next=http%3A%2F%2Fwww.facebook.com%2Fconnect%2Flogin_success.html&type=user_agent&perms=publish_stream&fbconnect=1");
}
function onLogout(result:Object):void
{
trace("Perfect Log Out!")
}
Have had this Android Facebook clean logout problem the whole day, manage to solve it. Hope it helps. Here is my FB mobile handlelogin code to ensure all fb cookies and sessions are being removed and user will need to relogin.
Sometimes FB server is very slow. Its best to put a timer before you call handleLoginClick() again
function handleLoginClick():void
{
trace("connecting to facebook");
if (FacebookMobile.getSession() == null)
{
FacebookMobile.init(APP_ID, onHandleInit, null);
FacebookMobile.manageSession = false
}
else
{
var webView:StageWebView = new StageWebView();
webView.viewPort = new Rectangle(0, 0, 1, 1);
webView.stage = this.stage;
webView.loadURL("https://m.facebook.com/logout.php?confirm=1&next=http://www.facebook.com&access_token=" + FacebookMobile.getSession().accessToken);
webView.addEventListener(Event.COMPLETE,webviewhandleLoad);
function webviewhandleLoad(e:Event)
{
FacebookMobile.logout(null, "http://apps.facebook.com/<appName>/");
FacebookMobile.logout(null, "http://www.facebook.com");
webView.dispose()
webView = null
setTimeout(handleLoginClick,3000)
}
}
}
look at the solution of this problem. Maby someone it helps:
var stage_ref:Stage = PlatformUtil.originalStage(); //my custom class to get stage
var webView:StageWebView = new StageWebView();
webView.viewPort = new Rectangle(0, 0, stage_ref.width, stage_ref.height);
FacebookMobile.login(loginCallback, stage_ref, appPermissions, webView);
http://code.google.com/p/facebook-actionscript-api/issues/detail?id=381
http://code.google.com/p/facebook-actionscript-api/issues/detail?id=382
http://code.google.com/p/facebook-actionscript-api/issues/detail?id=383