如何使用webview在Xamarin.iOS中实现手动Facebook登录

时间:2017-12-26 08:20:48

标签: ios facebook xamarin xamarin.ios

我正在尝试在我的Xamarin.iOS应用程序中实现Facebook登录。我曾尝试使用Xamarin.Auth包,但有时用户无法处理,此包存在一些问题。我发现最好的方法是实现手动登录流程到我的应用程序(使用Web视图)。目前,我在Faceboook开发人员门户中创建了一个应用程序,我可以从我的iOS应用程序访问该链接。

因此,用户将点击正常按钮,该按钮将被转发到Facebook登录页面。我的问题是,如何从Facebook登录页面获得结果?以及如何获得用户ID,电子邮件,......?

到目前为止,这是源代码:

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);
    }

1 个答案:

答案 0 :(得分:1)

我在下载官方SDK(Xamarin.Facebook.iOS)之后使用Facebook SDK找到答案,目前这被认为是最好的现有解决方案,以下是步骤:

  1. 在Info.plist文件中,添加以下代码:
  2. <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. 同样在Info.plist文件中,原始视图,高级选项卡,URL类型,像这样添加你的Facebook应用ID“fb1112222 ......”。保持'fb'开头。
    2. Pic: Facebook app ID in Info.plist

      1. 在AppDelegate.cs中,覆盖以下方法:

            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. 最后,这是Facebook的功能,您可以使用自己的按钮,或使用您的按钮。在我的方式,我使用我的按钮名称(BtnFacebookLogin)。

        //这是facebook功能

        private void SetupFacebookLoginButton()         {             列出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
        
                    });
                }
            }
        
      3. 有关详情,请参阅GitHub中的样本(Link