我目前正在iOS项目上使用Xamarin.Auth来处理一些用户身份验证,通过我的应用程序中的Facebook和Twitter。使用OAuth2Authenticator进行Facebook身份验证的效果很好,我的实现主要基于文档(http://components.xamarin.com/gettingstarted/xamarin.auth)。但Twitter仍然使用OAuth1,因此我基于我的实现主要取决于此StackOverflow问题(https://stackoverflow.com/a/21982205)中的答案。一切工作正常,我能够检索用户,微博等,但毕竟代码执行后,我收到一个“身份验证错误”弹出屏幕上显示“对象引用未设置为对象的实例”。没有任何东西印在控制台上,但正如我迄今为止所看到的最常见的错误一样。我可以关闭弹出窗口,并且所有内容都会继续正确预览。我相信我已经将问题缩小到了OAuth1Authenticator请求的范围内,因为当所有其他处理代码都被注释掉时,我仍然收到错误。请参考下面的代码来查看可能的原因。为什么Xamarin.Auth抛出认证错误OAuth1Authenticator和Twitter
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();
你解决这个问题? –