简体   繁体   中英

How to implement manual Facebook login in Xamarin.iOS using webview

I'm trying to implement Facebook login in my Xamarin.iOS application. I have tried to use Xamarin.Auth package, but sometimes user cannot processed and there are some issues with this package. I found the best way is to implement manual login flow to my application (using web-view). Currently, I have created an app in Faceboook developer portal, and I can access the link from my iOS application.

So, user will click normal button which will be forwarded to Facebook login page. My question is, how can I get the result from Facebook login page? and how can I get user id, email, ... ?

Here is the source code so far:

partial void BtnFacebookLogin_TouchUpInside(UIButton sender)
    {
        NSUrl apiRequest =
            new NSUrl("https://www.facebook.com/dialog/oauth?client_id="
            + SharedResources.fbClientId
            + "&response_type=token&redirect_uri="
            + SharedResources.fbRedirectUrl);

        UIApplication.SharedApplication.OpenUrl(apiRequest);
    }

I found the answer by using Facebook SDK, which is currently considered as the best existing solution, after your download the official SDK (Xamarin.Facebook.iOS), here are the steps:

  1. In Info.plist file, add these codes:

 <key>NSAppTransportSecurity</key> <dict> <key>NSExceptionDomains</key> <dict> <key>facebook.com</key> <dict> <key>NSIncludesSubdomains</key> <true/> <key>NSThirdPartyExceptionRequiresForwardSecrecy</key> <false/> </dict> <key>fbcdn.net</key> <dict> <key>NSIncludesSubdomains</key> <true/> <key>NSThirdPartyExceptionRequiresForwardSecrecy</key> <false/> </dict> <key>akamaihd.net</key> <dict> <key>NSIncludesSubdomains</key> <true/> <key>NSThirdPartyExceptionRequiresForwardSecrecy</key> <false/> </dict> </dict> </dict> <key>LSApplicationQueriesSchemes</key> <array> <string>fbapi</string> <string>fbapi20130214</string> <string>fbapi20130410</string> <string>fbapi20130702</string> <string>fbapi20131010</string> <string>fbapi20131219</string> <string>fbapi20140410</string> <string>fbapi20140116</string> <string>fbapi20150313</string> <string>fbapi20150629</string> <string>fbauth</string> <string>fbauth2</string> <string>fb-messenger-api20140430</string> <string>fb-messenger-api</string> <string>fbauth2</string> <string>fbshareextension</string> </array> 

  1. Also in Info.plist file, the original view, Advanced tab, URL Types, add your facebook app ID like this way "fb1112222......". Keep 'fb' at the beginning.

Pic: Facebook app ID in Info.plist

  1. In AppDelegate.cs, override these methods:

      public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) { // Override point for customization after application launch. // If not required for your application you can safely delete this method Profile.EnableUpdatesOnAccessTokenChange(true); Settings.AppID = "fb app id"; Settings.DisplayName = "fb app name"; // This method verifies if you have been logged into the app before, and keep you logged in after you reopen or kill your app. return ApplicationDelegate.SharedInstance.FinishedLaunching(application, launchOptions); //return true; } public override bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation) { // We need to handle URLs by passing them to their own OpenUrl in order to make the SSO authentication works. return ApplicationDelegate.SharedInstance.OpenUrl(application, url, sourceApplication, annotation); } 
  2. Lastly, this is the function for Facebook, you can use their own button, or use your button. In my way, I used my button with the name (BtnFacebookLogin).

    //Here is the facebook function

    private void SetupFacebookLoginButton() { List readPermissions = new List { "public_profile", "email" };

      ////Set Up Button Design var fbBtnText = new NSAttributedString("login with facebook", new UIStringAttributes() { ForegroundColor = UIColor.White }); BtnFacebookLogin.SetAttributedTitle(fbBtnText, UIControlState.Normal); BtnFacebookLogin.SetBackgroundImage( UIImage.FromBundle("btn_long_blue.png"), UIControlState.Normal); //Strat Login Functions Profile.Notifications.ObserveDidChange((sender, e) => { if (e.NewProfile == null) return; if (AccessToken.CurrentAccessToken != null) { var request = new GraphRequest("/me?fields=name,email", null, AccessToken.CurrentAccessToken.TokenString, null, "GET"); request.Start((connection, result, error) => { // Handle if something went wrong with the request if (error != null) { showAlert("Error", error.Description); return; } fbReponseFromSDK facebookSDKLoginItem = new fbReponseFromSDK(); // Get your profile name var userInfo = result as NSDictionary; if(userInfo["id"] != null) { Console.WriteLine("id is: " + userInfo["id"].ToString()); } if (userInfo["name"] != null) { Console.WriteLine("name is: " + userInfo["name"].ToString()); } if (userInfo["email"] != null) { Console.WriteLine("email is: " + userInfo["email"].ToString()); } //(Success) Do what you want next : doneFacbookLogin(); }); } }); // Handle actions once the user is logged in BtnFacebookLogin.ReadPermissions = readPermissions.ToArray(); BtnFacebookLogin.Completed += (sender, e) => { if (e.Error != null) { // Handle if there was an error showAlert("Facebook Login", e.Error.Description); return; } if (e.Result.IsCancelled) { // Handle if the user cancelled the login request //showAlert("Facebook Login", "Login Cancelled"); return; } showAlert("Facebook Login", "Login Successfull"); }; // Handle actions once the user is logged out BtnFacebookLogin.LoggedOut += (sender, e) => { // Handle your logout }; // If you have been logged into the app before, ask for the your profile name if (AccessToken.CurrentAccessToken != null) { var request = new GraphRequest("/me?fields=name,email", null, AccessToken.CurrentAccessToken.TokenString, null, "GET"); request.Start((connection, result, error) => { // Handle if something went wrong with the request if (error != null) { showAlert("Error", error.Description); return; } // Get your profile name }); } } 

For more info, refere to their samples in GitHub ( Link )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM