我目前在 iOS 项目上使用 Xamarin.Auth 在我的应用程序中通过 Facebook 和 Twitter 处理一些用户身份验证。使用 OAuth2Authenticator 的 Facebook 身份验证效果很好,我的实现主要基于文档 ( http://components.xamarin.com/gettingstarted/xamarin.auth )。然而,Twitter 似乎仍然使用 OAuth1,因此我的实现主要基于这个 StackOverflow 问题的答案(https://stackoverflow.com/a/21982205)。一切正常,我能够检索用户、推文等,但在所有代码执行后,我在屏幕上收到“身份验证错误”弹出窗口,显示“对象引用未设置为对象的实例”。控制台上没有打印任何内容,但是到目前为止我看到的大多数正常错误都是如此。我可以关闭弹出窗口,一切都会继续正确执行。我相信我已经将问题缩小到 OAuth1Authenticator 请求中的某些内容,因为当所有其他处理代码都被注释掉时,我仍然收到错误消息。请参考下面的代码,看看可能是什么原因造成的。
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
signupBtn.TouchUpInside += delegate {
LoginToTwitter(true, this);
};
}
void LoginToTwitter(bool allowCancel, UIViewController _vc)
{
var auth = new OAuth1Authenticator (
consumerKey: "My Consumer Key",
consumerSecret: "My Consumer Secret",
requestTokenUrl: new Uri("https://api.twitter.com/oauth/request_token"),
authorizeUrl: new Uri("https://api.twitter.com/oauth/authorize"),
accessTokenUrl: new Uri("https://api.twitter.com/oauth/access_token"),
callbackUrl: new Uri("My callback url"),
getUsernameAsync: (IDictionary<string, string> accountProperties) => {
string screen_name = "";
if (accountProperties.TryGetValue("screen_name", out screen_name)) {
Console.WriteLine("SN: {0}", screen_name);
Account a = new Account(screen_name, accountProperties);
AuthenticatorCompletedEventArgs e = new AuthenticatorCompletedEventArgs(a);
TwitterCompleted(e, _vc);
}
return null;}
);
auth.AllowCancel = allowCancel;
UIViewController authView = auth.GetUI ();
_vc.PresentViewController (authView, true, null);
}
void TwitterCompleted (AuthenticatorCompletedEventArgs e, UIViewController _vc)
{
var theAccount = e.Account;
var theProperties = theAccount.Properties;
foreach (var item in theProperties) {
Console.WriteLine (item); //debugging
}
InvokeOnMainThread (delegate {
_vc.DismissViewController (true, null);
});
AccountStore.Create ().Save (e.Account, "Twitter");
if (!e.IsAuthenticated) {
Console.WriteLine("Not authorized");
return;
}
theScreenName = e.Account.Properties["screen_name"];
theCount = "2";
IDictionary<string, string> theDict = new Dictionary<string, string>();;
theDict.Add("screen_name", theScreenName);
theDict.Add("count", theCount);
var request = new OAuth1Request("GET", new Uri("https://api.twitter.com/1.1/statuses/user_timeline.json"), theDict, e.Account, false);
request.GetResponseAsync().ContinueWith (t => {
if (t.IsFaulted)
Console.WriteLine("Error: {0}", t.Exception.InnerException.Message);
else if (t.IsCanceled)
Console.WriteLine("Canceled");
else
{
var obj = JsonValue.Parse (t.Result.GetResponseText());
Console.WriteLine("object: {0}", obj); // debugging
}
}, uiScheduler);
return;
}
private readonly TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();