Since Xamarin published the Xamarin 3 I have been playing with this.
Normally I develop apps for Windows Phone and Windows Store, and when i started to use some libraries related with Xamarin, I found some that libraries don´t use the async/awaitconcept, and for me is a fundamental.
One library that I think should use async/await but that I saw don´t use is the Xamarin.Auth!
For how that uses Xamarin.Auth.OAuth2Authenticator for authentication I recommend this solution:
For Xamarin.Android
public async Task<AuthenticatorCompletedEventArgs> LoginAsync(Activity activity, bool allowCancel)
{
var auth = new OAuth2Authenticator(
clientId: "<scopes here>",
scope: "<scopes here>",
authorizeUrl: new Uri("<url here>"),
redirectUrl: new Uri("<url here>"))
{
AllowCancel = allowCancel
};
var tcs1 = new TaskCompletionSource<AuthenticatorCompletedEventArgs>();
EventHandler<AuthenticatorCompletedEventArgs> d1 =
(o, e) =>
{
try
{
tcs1.TrySetResult(e);
}
catch (Exception ex)
{
tcs1.TrySetResult(new AuthenticatorCompletedEventArgs(null));
}
};
auth.Completed += d1;
var intent = auth.GetUI(activity);
activity.StartActivity(intent);
var result = await tcs1.Task;
auth.Completed -= d1;
return result;
}
And then we need to call it this way:
var authService = new AuthService();
var result = await authService.LoginAsync(this, allowCancel);
For Xamarin.IOS
public async Task<Account> LoginAsync(DialogViewController dialog, bool allowCancel)
{
var auth = new OAuth2Authenticator(
clientId: "<scopes here>",
scope: "<scopes here>",
authorizeUrl: new Uri("<url here>"),
redirectUrl: new Uri("<url here>"))
{
AllowCancel = allowCancel
};
var tcs1 = new TaskCompletionSource<AuthenticatorCompletedEventArgs>();
EventHandler<AuthenticatorCompletedEventArgs> d1 =
(o, e) =>
{
try
{
tcs1.TrySetResult(e);
}
catch (Exception ex)
{
tcs1.TrySetResult(new AuthenticatorCompletedEventArgs(null));
}
};
try
{
auth.Completed += d1;
var vc = auth.GetUI();
dialog.PresentViewController(vc, true, null);
var result= await tcs1.Task;
return result.Account;
}
catch (Exception)
{
return null;
}
finally
{
auth.Completed -= d1;
}
}
And then we need to call it this way:
var authService = new AuthService();
var result = await authService.LoginAsync(dialog, allowCancel);
In conclusion, i think it is very simple to use and i think it should be add to the Xamarin.Auth.
I added the sample to:
https://github.com/saramgsilva/Xamarin.Auth/tree/master/samples
and will do a pull request for the original repository.