Facebook Native Login With Xamarin.Forms

Introduction and History

Social login is a standout among the essential highlights of an application. It's the principal connection of a client with our work and must be simple, straightforward, and dependable. In light of this, I chose, together with my companion Afzaal Ahmed, to begin a progression of posts with what we believe are the best ways to deal with, doing social login with all the significant web-based social networking players. How about we begin with Facebook?

There are numerous modules to use on Xamarin.Forms to actualize validation with Facebook. Lamentably for every one of the ones that I attempted, the default alternative is to show a WebView where the client needs to sort their Facebook certifications or profound connection Facebook in the client's program. Imagine a scenario where the client has Facebook application introduced in his gadget. We need our application to utilize it!

Xamarin has made Xamarin.Facebook.Android and Xamarin.Facebook.iOS, both accessible. They are an interpretation of Facebook's local SDK into C#. We will utilize them to execute the local login stream for Facebook on Android and iOS with Xamarin.Forms.

Facebook App Setup

I won’t go into much detail on how to create a Facebook App, only how to set it up for what we want to do here. For detailed information, you can check @tim_lariviere's post here. He did a great job explaining the process step by step, or you can also check out Facebook’s official docs here.

Xamarin

Once our Facebook App, named Xamarin-Auth, is created and all set on the developer’s portal, go to Settings > Basic on the side menu. On this page, we will set up the access to iOS and Android platforms.

After this, select the “add platform button”, and add the Android and iOS options to your Xamarin-Auth app.

Xamarin

Facebook Android Setup

To design the Android app, a bundle name, a class name, and a hash key are required. You can discover the package name of the Android application at Xamarin.Android venture, on the AndroidManifest.xml record. For the class name, how about we utilize MainActivity; and for the hash key, you should open cmd or terminal and sort changing the[USERNAME] tag to your own:

Code

Mac: keytool -exportcert -alias androiddebugkey -keystore /Users/[USERNAME]]/.local/share/Xamarin/Mono\ for\ Android/debug.keystore | openssl sha1 -binary | openssl base64 

Windows: keytool -exportcert -alias androiddebugkey -keystore "C:\Users\[USERNAME]\AppData\Local\Xamarin\Mono for Android\debug.keystore" | openssl sha1 -binary | openssl base64         

The terminal or cmd will request a secret key, then it will give you the hash key. Glue the hash key and the bundle name on the Android stage and hit the spare catch on the base of the page.

Xamarin

Xamarin iOS Setup

For iOS, the setup is simpler. Just add the bundle id of your app to the iOS window and hit "Save" at the bottom of the page.

Xamarin

Xamarin Android Project Setup

Now, let’s setup our Xamarin.Droid project with the required information for it to work properly. You can also follow the guide made by Facebook here.

  • Download Xamarin.Facebook.Android(vs4.26)SDK, on the Android project via NuGet.
  • Paste this code on the strings.xmlfile/values/strings.xml, replacing the Xamarin-Auth app id.
    1. <string name="facebook_app_id"><YOUR APP ID></string>  
  • Open AndroidManifest.xml and add a user-permission element to the file.
    1. <application android:label="@string/app_name" ...>  
    2.     ...  
    3.     <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>  
    4.     ...  
    5. </application> 
  • Open MainActivity.cs and inside OnCreate method, add Facebook SDK initialization.

    Code
    1. protected override void OnCreate(Bundle bundle)  
    2.         {  
    3.             TabLayoutResource = Resource.Layout.tabs;  
    4.             ToolbarResource = Resource.Layout.toolbar;  
    5.    
    6.             base.OnCreate(bundle);  
    7.             FacebookSdk.SdkInitialize(this);  
    8.    
    9.             global::Xamarin.Forms.Forms.Init(this, bundle);  
    10.             LoadApplication(new App(new AndroidInitializer()));  
    11.         }  
  • Override the following method on MainActivity.cs.
    1. protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)  
    2.         {  
    3.             base.OnActivityResult(requestCode, resultCode, data);  
    4.             var manager = DependencyService.Get<IFacebookManager>();  
    5.             if (manager != null)  
    6.             {  
    7.                 (manager as FacebookManager)._callbackManager.OnActivityResult(requestCode, (int)resultCode, data);  
    8.             }  
    9.         } 

Xamarin iOS Project Setup

It is time for Xamarin.iOS to find the info.plist file and open it in the XML Editor.

  • Download Xamarin.Facebook.iOS SDK(vs4.24) on the iOS project via NuGet. 
  • Copy and paste the XML snippet into the body of your file (inside the <dict> tag) replacing the AuthenticationExample app id.

Code

  1. <key>CFBundleURLTypes</key>  
  2. <array>  
  3.   <dict>  
  4.   <key>CFBundleURLSchemes</key>  
  5.   <array>  
  6.     <string>fb<YOUR APP ID></string>  
  7.   </array>  
  8.   </dict>  
  9. </array>  
  10. <key>FacebookAppID</key>  
  11. <string><YOUR APP ID></string>  
  12. <key>FacebookDisplayName</key>  
  13. <string>AuthenticationExample</string>  
  14. <key>LSApplicationQueriesSchemes</key>  
  15. <array>  
  16.   <string>fbapi</string>  
  17.   <string>fb-messenger-api</string>  
  18.   <string>fbautstrong</string>  
  19.   <string>fbshareextension</string>  
  20. </array>  
Open AppDelegate.cs and override the following methods.

Code

  1. public override void OnActivated(UIApplication uiApplication)  
  2.         {  
  3.             base.OnActivated(uiApplication);  
  4.             AppEvents.ActivateApp();  
  5.         }  
  6.    
  7.         public override bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)  
  8.         {  
  9.             //return base.OpenUrl(application, url, sourceApplication, annotation);  
  10.             return ApplicationDelegate.SharedInstance.OpenUrl(application, url, sourceApplication, annotation);  
  11.         }  
Let’s code!

Goodness, that was a ton of set up! We should get to the coding now.

Me and my companion Afzaal assembled a repo on GitHub that has a working case. On the off chance that you need to, don't hesitate to clone, fork, and utilize it. You can discover it here, under the FacebookNativeLogin organizer. It is an extremely basic, single page at Xamarin.Forms that utilizes Dependency Injection and agents the Login and Logout activities at the local stages. At that point, by means of an action, we get the Facebook user information back in the Xamarin.Forms venture.

Project Tech info

  • Forms 2.4.0
  • Prism 6.3.0
  • Facebook.Android 4.26 (On the Xamarin.Droid project)
  • Facebook.iOS 4.24 (On the Xamarin.iOS project)

On the Forms project, we have a contract with two signatures.

  1. public interface IFacebookManager  
  2.     {  
  3.         void Login(Action<FacebookUser, string> onLoginComplete);  
  4.         void Logout();  
  5.     }  

Both methods are implemented in Android project and in the iOS project. After the execution of the login, the OnLoginComplete method will be invoked, adding the user Facebook object to the ViewModel binding.

Code

  1. private void OnLoginComplete(FacebookUser facebookUser, string message)  
  2.         {  
  3.             if (facebookUser != null)  
  4.             {  
  5.                 FacebookUser = facebookUser;  
  6.                 IsLogedIn = true;  
  7.             }  
  8.             else  
  9.             {  
  10.                 _dialogService.DisplayAlertAsync("Error", message, "Ok");  
  11.             }  
  12.         }  

CAUSER TIP

On the off chance you may experience difficulty executing the hash summon on Windows; you should include the required System Variables so you can execute it.

I experienced difficulty with the most recent rendition of the Xamarin.Facebook.iOS bundle. On a genuine gadget, it wasn't identifying the Facebook application introduced in the client's gadget. So, I downsized it from form 4.26 to 4.24. At that point, it worked flawlessly.

References

  • https://github.com/mikeapple/XamarinFormsNativeFBLogin/
  • https://github.com/xamarin/Xamarin.Auth
  • https://github.com/HoussemDellai/Xamarin.Auth
  • https://github.com/nosmirck/Xamarin.Forms.Social
  • https://github.com/DanielCauser/SocialLoginSamples
  • https://developers.facebook.com/quickstarts?platform=android
  • https://developers.facebook.com/quickstarts?platform=ios
  • https://developer.xamarin.com/guides/xamarin-forms/cloud-services/authentication/oauth/
  • http://timothelariviere.com/2017/10/11/authenticate-users-through-facebook-using-xamarin-auth/
  • https://developers.facebook.com/
  • https://www.youtube.com/watch?v=cyq_ho4QflQ
  • https://www.youtube.com/watch?v=YpkqOjw38ds&feature=youtu.be

Up Next
    Ebook Download
    View all
    Learn
    View all