我正在为我的应用程序使用xamarin.forms。 它允许用户通过Facebook登录。 我在应用程序中添加了一个注销按钮,以简单地导航回到登录页面,但是我注意到,当我退出我的应用程序而不按注销按钮时,该应用程序将在登录页面恢复(导致用户每次都不断输入其登录详细信息 他们必须重新打开该应用程序)。 关闭并重新打开应用程序后,如何保持用户登录状态? 任何指导对此将不胜感激。
App.cs(MainPage是我的登录页面)
public App() { InitializeComponent(); MainPage = new NavigationPage(new MainPage()); } public async static Task NavigateToSMS() { await App.Current.MainPage.Navigation.PushAsync(new SMS()); } public static void NavigateToProfile() { App.Current.MainPage = (new InvalidLogin()); } public static void NavigateToVerified() { App.Current.MainPage = (new Profile()); } protected override void OnStart() { // Handle when your app starts } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app sleeps } |
Facebook渲染
[assembly: ExportRenderer(typeof(Login), typeof(LoyaltyWorx.Droid.FacebookRender))] namespace LoyaltyWorx.Droid { public class FacebookRender : PageRenderer { public FacebookRender() { String error; var activity = this.Context as Activity; var auth = new OAuth2Authenticator( clientId:"", scope:"email", authorizeUrl: new Uri("https://www.facebook.com/dialog/oauth/"), redirectUrl: new Uri("https://www.facebook.com/connect/login_success.html") ); auth.Completed += async (sender, eventArgs) => { try { if (eventArgs.IsAuthenticated) { await AccountStore.Create().SaveAsync(eventArgs.Account,"FacebookProviderKey"); var accessToken = eventArgs.Account.Properties["access_token"].ToString(); var expiresIn = Convert.ToDouble(eventArgs.Account.Properties["expires_in"]); var expiryDate = DateTime.Now + TimeSpan.FromSeconds(expiresIn); var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me?fields=email,first_name,last_name,gender,picture"), null, eventArgs.Account); var response = await request.GetResponseAsync(); var obj = JObject.Parse(response.GetResponseText()); var id = obj["id"].ToString().Replace(""",""); var name = obj["first_name"].ToString().Replace(""",""); var surname = obj["last_name"].ToString().Replace(""",""); var gender = obj["gender"].ToString().Replace(""",""); var email = obj["email"].ToString().Replace(""",""); Customer.Customers cust = new Customer.Customers(); cust.Number =""; cust.Name = name; cust.Surname = surname; cust.Address ="sample"; cust.Email = email; cust.City ="DBN"; cust.Region ="KZN"; cust.Country ="SA"; cust.MobilePhone =""; cust.DOB = DateTime.Now; cust.Phone =""; cust.Credentials = new Customer.Credentials(); cust.Credentials.Authenticated = true; cust.Credentials.SecretKey ="73fnfdbjfdj"; cust.DeviceToken = GcmService.RegistrationID; CustomerService service = new CustomerService(); Settings.Token = await service.AddCustomer(cust); if (Settings.MobileNo == null || Settings.MobileNo =="") { await App.NavigateToSMS(); } else { App.NavigateToVerified(); } } else { App.NavigateToProfile(); } } catch(Exception ex) { error = ex.Message; } }; activity.StartActivity(auth.GetUI(activity)); } } } |
用户登录后出现的页面
namespace LoyaltyWorx { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class Profile : MasterDetailPage { public List<MasterPageItem> menuList { get; set; } public Profile() { InitializeComponent(); this.lblMessage.Text = Settings.Name +"" + Settings.Surname; menuList = new List<MasterPageItem>(); var page1 = new MasterPageItem() { Title ="Home", Icon ="home.png", TargetType = typeof(Page1) }; var page2 = new MasterPageItem() { Title ="Cards", Icon ="card.png", TargetType = typeof(Cards) }; var page3 = new MasterPageItem() { Title ="Transactions", Icon ="settings.png", TargetType = typeof(Transactions) }; var page4 = new MasterPageItem() { Title ="My Profile", Icon ="profile.png", TargetType = typeof(UpdateProfile) }; var page5 = new MasterPageItem() { Title ="Log out", Icon ="signout.png", TargetType = typeof(MainPage) }; menuList.Add(page1); menuList.Add(page2); menuList.Add(page3); menuList.Add(page4); menuList.Add(page5); navigationDrawerList.ItemsSource = menuList; Detail = new NavigationPage((Page)Activator.CreateInstance(typeof(Page1))); } private void OnMenuItemSelected(object sender, SelectedItemChangedEventArgs e) { var item = (MasterPageItem)e.SelectedItem; Type page = item.TargetType; Detail = new NavigationPage((Page)Activator.CreateInstance(page)); IsPresented = false; } } } |
设置类别:存储登录用户的详细信息
|
public static class Settings { public static string Token; public static int CustId; public static string Name; public static string Surname; public static string Email; public static string MobileNo; public static string PhoneNo; } |
App.cs-更新
|
public App() { App.Current.Properties["UserDetail"] = Settings.Token; InitializeComponent(); var isLoggedIn = Current.Properties.ContainsKey("UserDetail"); if (!isLoggedIn) { MainPage = new NavigationPage(new MainPage()); } else { App.Current.MainPage = (new Profile()); } } |
每次启动应用程序时,您都在加载MainPage。您必须有条件地加载第一页。
Xamarin.Forms实现Application.Current.Properties,该属性将键值数据存储在应用程序的本地存储中。
登录时:
成功登录后,将" True"值存储在应用程序的本地存储中,如IsLoggedIn所示,如下所示:
1 |
Application.Current.Properties ["IsLoggedIn"] = Boolean.TrueString; |
在应用启动时(App.cs)
|
public App() { InitializeComponent(); bool isLoggedIn = Current.Properties.ContainsKey("IsLoggedIn") ? Convert.ToBoolean(Current.Properties["IsLoggedIn"]) : false; if (!isLoggedIn) { //Load if Not Logged In MainPage = new NavigationPage(new MainPage()); } else { //Load if Logged In MainPage = new NavigationPage(new YourPageToLoadIfUserIsLoggedIn()); } } |
登出时:
注销时,将False值存储在IsLoggedIn本地存储密钥中,然后清除导航堆栈并加载MainPage。
Application.Current.Properties ["IsLoggedIn"] = Boolean.FalseString; |
存储用户详细信息:
要存储Settings类对象的值,请将其序列化为Json(Nuget包)字符串对象,并将其存储在其他某个键中,例如Application.Current.Properties中的UserDetail。
当您需要这些数据时,请从本地存储中获取数据并对其进行反序列化并使用它。
商店:App.Current.Properties["UserDetail"] = JsonConvert.SerializeObject(Settings);
检索:Settings userData = JsonConvert.DeserializeObject(App.Current.Properti??es["UserDetail"]);
编辑
Current.Properties.ContainsKey只是检查存储中是否存在某些密钥。它不检查值是否存在。在访问任何键值之前,有必要检查该键是否存在。
静态类无法序列化,因此您需要创建该类的Singleton实例,然后访问该Singleton实例进行序列化。
希望这会有所帮助!
Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有