Xamarin开发登录示例
Xamarin开发登录示例
登录视图模型:
class LoginViewModel
{
public string Email { get; set; }
public string Password { get; set; }
public ICommand LoginCommand
{
get
{
return new Command(async () =>
{
ApiServices apiServices = new ApiServices();
var accesstoken = await apiServices.LoginUserAsync(Email, Password);
Settings.AccessToken = accesstoken;
});
}
}
public LoginViewModel()
{
Email = Settings.Username;
Password = Settings.Password;
}
}
登录:
public async Task<string> LoginUserAsync(string email, string password)
{
var client = new HttpClient();
var keyValues = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("username", email),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("grant_type", "password")
};
var request = new HttpRequestMessage(
HttpMethod.Post, "linktotoken");
request.Content = new FormUrlEncodedContent(keyValues);
var reponse = await client.SendAsync(request);
var jwt = await reponse.Content.ReadAsStringAsync();
JObject jwtDyanmic = JsonConvert.DeserializeObject<dynamic>(jwt);
var accessToken = jwtDyanmic.Value<string>("access_token");
var accessTokenExpiration = jwtDyanmic.Value<DateTime>(".expires");
Settings.AccessTokenExpiration = accessTokenExpiration;
Debug.WriteLine(jwt);
return accessToken;
}
LoginPage.xaml:
<ContentPage.BindingContext>
<vm:LoginViewModel/>
</ContentPage.BindingContext>
<StackLayout VerticalOptions="Center">
<Entry Text="{Binding Email}" />
<Entry Text="{Binding Password}" />
<Button Command="{Binding LoginCommand}" Text="Login/Signin" />
</StackLayout>
App.xaml.cs
public App ()
{
InitializeComponent();
SetMainPage();
}
private void SetMainPage()
{
if (!string.IsNullOrEmpty(Settings.AccessToken))
{
if (DateTime.UtcNow.AddHours(1) > Settings.AccessTokenExpiration)
{
var vm = new LoginViewModel();
vm.LoginCommand.Execute(null);
}
MainPage = new NavigationPage(new GSMUnitsPage());
}
else if(!string.IsNullOrEmpty(Settings.Username) && !string.IsNullOrEmpty(Settings.Password))
{
MainPage = new NavigationPage(new LoginPage());
}
else
{
MainPage = new NavigationPage(new RegisterPage());
}
}
此事例关键是要关注一个问题,它不同于安卓原生的方式登陆成功后关闭登陆页面,这里是采用重新指定mainpage也就是根页面的方式达到目的