我正在尝试为Xamarin.Android创建一个登录系统以在解析服务器上使用.我想用Facebook登录该用户,并保存他的真实姓名和小用户照片.
我当前显示登录系统的代码是这样的:
using Xamarin.Auth;loginFacebookbutton.Click += (sender, e) => { if (CrossConnectivity.Current.IsConnected) LoginToFacebook(); else { displayNoConnectivityMessage(); } }; loginTwitterbutton.Click += (sender, e) => { LoginToTwitter(); }; } voID displayNoConnectivityMessage() { AlertDialog.Builder alert2 = new AlertDialog.Builder(this); alert2.Set@R_404_5979@("Network error"); alert2.SetMessage("Connection with the Internet is required. Please check your connectivity and try again."); alert2.Show(); } voID displayLoadingMessage(bool dismiss) { RunOnUiThread(() => { if (!dismiss) { builder = new AlertDialog.Builder(this); builder.Set@R_404_5979@("Signing in"); builder.SetMessage("Please wait..."); builder.SetCancelable(false); alert = builder.Create(); alert.Show(); } else { if (alert != null) if (alert.IsShowing) { alert.dismiss(); alert.dispose(); } } }); } async voID LoginToFacebook() { var auth = new OAuth2Authenticator( clIEntID: "809804315805408", scope: "user_about_me", authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"), redirectUrl: new Uri("http://www.facebook.com/connect/login_success.HTML") ); auth.AllowCancel = false; // If authorization succeeds or is canceled, .Completed will be fired. auth.Completed += LoginComplete; var intent = auth.GetUI(this); StartActivity(intent); } public async voID LoginComplete(object sender, AuthenticatorCompletedEventArgs e) { string ID = ""; string name = ""; JsonValue obj; if (!e.IsAuthenticated) { var builder = new AlertDialog.Builder(this); builder.SetMessage("Not Authenticated"); builder.SetPositivebutton("Ok", (o, c) => { }); builder.Create().Show(); return; } else { displayLoadingMessage(false); AccountStore.Create(this) .Save(e.Account, "Facebook"); // Now that we're logged in, make a OAuth2 request to get the user's info. var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me"), null, e.Account); await request.GetResponseAsync().ContinueWith(t => { var builder2 = new AlertDialog.Builder(this); if (t.IsFaulted) { builder2.Set@R_404_5979@("Error"); builder2.SetMessage(t.Exception.Flatten().InnerException.ToString()); builder2.Show(); } else if (t.IsCanceled) { builder2.Set@R_404_5979@("Task Canceled"); builder2.Show(); } else { obj = JsonValue.Parse(t.Result.GetResponseText()); ID = obj["ID"]; name = obj["name"]; } builder.SetPositivebutton("Ok", (o, c) => { }); builder.Create(); }, UIScheduler); var accesstoken = e.Account.PropertIEs["access_token"]; var expiresIn = Convert.Todouble(e.Account.PropertIEs["expires_in"]); var expiryDate = DateTime.Now + TimeSpan.FromSeconds(expiresIn); var user = await ParseFacebookUtils.LogInAsync(ID, accesstoken, expiryDate); try { user.Add("name", name); } catch (Exception ex) { Console.Writeline("LoginFragment.cs | LoginComplete() :: user.Add (\"name\",name); :: " + ex.Message); } var webClIEnt = new WebClIEnt(); //var httpClIEnt = new httpClIEnt(new NativeMessageHandler()); var url = new Uri("http://graph.facebook.com/" + ID + "/picture?type=small"); application.currentUserImageUrl = url.ToString(); application.currentUsername = name; byte[] bytes = null; //bytes = await httpClIEnt.GetByteArrayAsync(url); bytes = await webClIEnt.DownloadDataTaskAsync(url); Parsefile saveImagefile = new Parsefile("profileImage.jpg", bytes); try { user.Add("profile_pic", saveImagefile); } catch (Exception ex) { Console.Writeline("LoginFragment.cs | LoginComplete() :: user.Add (\"profile_pic\",saveImagefile); :: " + ex.Message); } application.currentUser = user; await user.SaveAsync(); displayLoadingMessage(true); ChangeScreen(); } }
此代码的问题是这样的:
>登录后,我会显示一条成功消息(简单
白页上的成功消息)必须来自Facebook和
显然,我不愿意在用户身上显示.
>虽然
LoginCompete代码正在运行,应用程序正在后台运行,并且用户看不到任何提示,就像应用程序关闭后
登录再次打开.我试图显示一个AlertDialog与
函数displayNoConnectivityMessage但未显示
在用户什么我不知道的方式.
解决方法:
在Parse上用Facebook登录的最简单方法是将官方的Parse SDK与官方的AndroID SDK版Facebook结合使用以处理单一登录方案.
仅需一些小步骤,即可达到预期的结果:
>按照此小型指南为Facebook SDK设置应用:https://components.xamarin.com/gettingstarted/facebookandroid
>设置解析SDK
public App(){ // App.xaml initialization ParseClIEnt.Initialize("Your Application ID", "Your .NET Key"); ParseFacebookUtils.Initialize("Your Facebook App ID"); // Other initialization}
>将FB登录按钮添加到视图中.
<com.facebook.login.Widget.Loginbutton androID:ID="@+ID/login_button" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_gravity="center_horizontal" androID:layout_margintop="30dp" androID:layout_marginBottom="30dp" />
>获取回调,并使用令牌通过Parse登录用户.
public class MainActivity : Activity, IFacebookCallback{ protected overrIDe voID OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our vIEw from the "main" layout resource // SetContentVIEw (Resource.Layout.Main); var callbackManager = CallbackManagerFactory.Create(); var loginbutton = FindVIEwByID<Loginbutton>(Resource.ID.login_button); loginbutton.RegisterCallback(callbackManager, this); } #region IFacebookCallback public voID OnCancel() { // Handle Cancel } public voID one rror(FacebookException error) { // Handle Error } public async voID OnSuccess(Object result) { // We kNow that this is a LoginResult var loginResult = (LoginResult) result; // Convert Java.Util.Date to DateTime var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); var expireDate = epoch.AddMilliseconds(loginResult.Accesstoken.Expires.Time); // FB User Accesstoken var accesstoken = loginResult.Accesstoken.Token; ParseUser user = await ParseFacebookUtils.LogInAsync("Your Facebook App ID", accesstoken, expireDate); } #endregion... }
>(可选)与Facebook SDK& ParseUser
// You can simply pass the acquired Accesstoken to the GraphRequestvar parameters = new Bundle();parameters.PutString("fIElds", "ID,email,gender,cover,picture.type(small)");var request = new GraphRequest(loginResult.Accesstoken, "me", parameters, httpMethod.Get);// Execute request and Handle response (See FB AndroID SDK GuIDe)// to get image as byte[] from GraphResponsebyte[] data;// Store the image into the ParseUseruser["image"] = new Parsefile("image.jpg", data);
Instead of using the GraphRequest you can always fallback to the
httpClIEnt
/ WebClIEnt and pass the Accesstoken as URL parameter. 07002
额外
这里是官方文档的链接:http://parseplatform.github.io/docs/dotnet/guide/#facebook-users
从Nuget选择SDK:https://www.nuget.org/packages/Xamarin.Facebook.Android/
Xamarin Facebook AndroID SDK的工作方式类似于Java SDK,因此,该文档也值得一看:https://developers.facebook.com/docs/facebook-login/android#addbutton
总结以上是内存溢出为你收集整理的C#-使用Xamarin.Android为Parse.com服务器制作更漂亮的Facebook登录屏幕全部内容,希望文章能够帮你解决C#-使用Xamarin.Android为Parse.com服务器制作更漂亮的Facebook登录屏幕所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)