保持用户登录xamarin.forms应用程序,除非点击注销



我的应用程序使用xamarin.forms。它允许用户通过facebook登录。我在应用程序中添加了一个注销按钮,只需导航回登录页面,但我注意到,当我在不按注销按钮的情况下退出应用程序时,应用程序会在登录页面上恢复(导致用户每次重新打开应用程序时都会不断输入登录详细信息)。当用户关闭并重新打开应用程序时,我如何保持用户登录?如有任何指导,我们将不胜感激。。

App.cs (主页是我的登录页面)

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
}

FacebookRender

[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)中,如下所示:

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(NugetPackage)字符串对象,并将其存储在其他一些键中,例如Application.Current.Properties中的UserDetail。当你需要这些数据时,从本地存储中提取并取消跟踪并使用它。

门店:App.Current.Properties["UserDetail"] = JsonConvert.SerializeObject(Settings);检索:Settings userData = JsonConvert.DeserializeObject<Settings>(App.Current.Properti‌​es["UserDetail"]);

编辑

Current.Properties.ContainsKey只是检查存储器中是否存在某个密钥。它不检查值是否存在。在访问任何键值之前,有必要检查该键值是否存在。

静态类无法序列化,因此需要创建该类的Singleton实例,然后访问该Singleton示例进行序列化。

希望这会有所帮助!!。

我使用设置插件解决了这个问题。工作完美!

最新更新