C# 使用Xamarin.Android为Parse.com服务器制作更漂亮的Facebook登录屏幕
我正在尝试为Xamarin.Android创建一个登录系统,以便在解析服务器上使用。我想用Facebook登录该用户,并保存其真实姓名和小用户照片。 我当前显示登录系统的代码如下:C# 使用Xamarin.Android为Parse.com服务器制作更漂亮的Facebook登录屏幕,c#,android,parse-platform,xamarin,facebook-login,C#,Android,Parse Platform,Xamarin,Facebook Login,我正在尝试为Xamarin.Android创建一个登录系统,以便在解析服务器上使用。我想用Facebook登录该用户,并保存其真实姓名和小用户照片。 我当前显示登录系统的代码如下: using Xamarin.Auth; loginFacebookButton.Click += (sender, e) => { if (CrossConnectivity.Current.IsConnected) LoginToFa
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.SetTitle("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.SetTitle("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.SetTitle("Error");
builder2.SetMessage(t.Exception.Flatten().InnerException.ToString());
builder2.Show();
}
else if (t.IsCanceled)
{
builder2.SetTitle("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登录的最简单方法是将官方与官方Facebook for Android SDK结合使用,以处理单一登录场景 只需一些小步骤,您就可以实现预期的结果:
public App()
{
// App.xaml initialization
ParseClient.Initialize("Your Application ID", "Your .NET Key");
ParseFacebookUtils.Initialize("Your Facebook App Id");
// Other initialization
}
<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" />
HttpClient
/WebClient,并将AccessToken作为URL参数传递
附加的
这里是官方文件的链接:
从Nuget中选择SDK:
Xamarin Facebook Android SDK的工作原理与Java SDK类似,因此本文档也值得一看:我的问题最终是:
但是paul Reichlet的答案是本机facebook登录的最佳方法。您的parsefacebookutil代码示例来自java,在c语言中,它没有这些参数(ParseFacebookUtils.LogInAsync(string FaceBookID、string AccessToken、DateTime expiration))而且它不提供UI。我还想要一种保存用户图像的方法,通过facebook sdk示例,我只看到一种显示用户图像的方法,而不是保存用户图像的方法。你是对的,高级解决方案是一个Java示例,需要一些自定义jar绑定才能与Xamarin一起工作。然而,您可以使用上述简单的解决方案。确保在调用
ParseFacebookUtils.LogInAsync(browser,null)之前打开浏览器
以查看OAuth登录页面。您可以使用FB Sdk或HttpClient从Graph API中获取图像,并将其保存在ParseUser中,其中user[“image”]=new ParseFile(“userimage.jpg”,data)代码>其中数据是下载图像的字节[]
。但是用于c#的ParseFacebookUtils没有接受浏览器的构造函数,参数为null,那么我怎么做?我真的很抱歉。我从我的一个旧应用程序中获取了这个。我更新到了最新的SDK版本,现在看到他们对API做了一些更改。我会尽快更新答案。谢谢,我会尽快测试你的代码,但如果我能找到一个使用Xamarin.Auth的解决方案,那就太好了,因为我想用更多的方式登录其他网站,我可能会再次遇到同样的问题
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 OnError(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
...
}
// You can simply pass the acquired AccessToken to the GraphRequest
var 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 GraphResponse
byte[] data;
// Store the image into the ParseUser
user["image"] = new ParseFile("image.jpg", data);