Hi,
I am using App.Current.Properties
to know if user has already logged in and redirect him to main page instead of the login page.
However, it seems that the property i am saving for that is not getting saved and i dont know why.
Here is the code when i save the property after the user logged in
public WelcomePage () { InitializeComponent(); App.SetProperties("IsLoggedIn", true); ... }
App class:
... bool isLoggedIn = Application.Current.Properties.ContainsKey("IsLoggedIn") ? Convert.ToBoolean(GetProperties("IsLoggedIn")) : false; //HERE ALWAYS GIVES ME FALSE NO MATTER WHAT if (!isLoggedIn) { ///colocar login page depois MainPage = new NavigationPageGradientHeader(new LoginPage()) { LeftColor = Color.FromHex("#4195D3"), RightColor = Color.FromHex("#0058A8") }; } else { MainPage = new NavigationPageGradientHeader(new MainPage()) { LeftColor = Color.FromHex("#4195D3"), RightColor = Color.FromHex("#0058A8") };
and function to add property
public async static void SetProperties(string property, object value) { var app = (App)Application.Current; app.Properties[property] = value; await app.SavePropertiesAsync(); }
Answers
@Kelve
(1) Are you testing on Android by any chance?
If so, in Visual Studio, go to Tools/Options/Xamarin/Android Settings
and then ensure that "Preserve application data cache on device between deploys" is checked.
(2) If you are using an emulator, see what happens on a physical device.
Regarding your code:
(3) Use
async Task
orasync Task<T>
rather thanasync void
for the signature of async methods, other than event handlers.(4) Will you ever set the IsLoggedIn property to false? If not, you can simplify the line
bool isLoggedIn = Application.Current.Properties.ContainsKey("IsLoggedIn") ? Convert.ToBoolean(GetProperties("IsLoggedIn")) : false;
to
bool isLoggedIn = Application.Current.Properties.ContainsKey("IsLoggedIn");
(5) To avoid typing errors causing problems, do not keep repeating the hard-coded string "IsLoggedIn". Use a static string instead that uses static initialisation and that is accessed everywhere you currently use the hard-coded string.
App.SetProperties("IsLoggedIn", true);
has been called inWelcomePage
, i see when you first login in , the page isLoginPage
, does WelcomePage locates in navigation stack after Login Page ?GetProperties
?Modify the code to
(1) Not just android.The option is checked. Im also debbuging to a real iOS device through wifi and it is also not working.
(4) Yes, i will set when the user logs out.
I test on my side everything is fine , could you provide a basic project for us to reproduce ?