Hello,
For the case of obtaining user information to determine the page display, it is recommended that you place it in the OnAppearing method of AppShell for the following reasons.
-
App.xaml.cs
is not a UI component. For UI initialization, it would be a better choice to write it inAppShell.xaml.cs
. -
HttpClient
initiates a request to the Service asynchronously, so it is necessary to use await when calling it, but theasync/await
keywords are not allowed in the constructor. Therefore, you can put this method in theOnAppearing
method ofAppShell.xaml.cs
to process this request when the UI is initialized.
protected override async void OnAppearing()
{
base.OnAppearing();
// Handle Http request here.
}
Updated:
This order is expected. Usually, when an app loads user data, it will first load a loading animation page instead of loading data when the app starts. Then decide whether to display the home page or the login page based on the network request. The reasons are as follows:
- Use animated pages to load data, and the page transition will be smoother.
- The API that requests user data is not guaranteed to be available all the time. For example, the user may be out of network, the server may be delayed, or the DNS resolution may be wrong. In these cases, if there is no page to remind the user that the program has encountered an error, the application will be stuck on the SplashScreen. On Windows platforms, this means that the window is not loaded after the application is opened.
In general, developers should avoid anything that would cause their app to lag on startup.
If you need to implement it in the order of requesting user data before loading, you need to add this method to the constructor of App. This will cause the program to be unable to handle the situation where the Task request fails.
You could refer to the following runable code sample:
public App()
{
InitializeComponent();
Debug.WriteLine("Start");
Task.Run( async() => await LoadedUserData("1"));
MainPage = new AppShell();
}
public async Task LoadedUserData(string userId)
{
try
{
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/todos/" + userId);
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
// Debug.WriteLine("189|content : " + content);
AppShell.userData = JsonSerializer.Deserialize<UserData>(content);
Debug.WriteLine("193|UserID : " + AppShell.userData.id);
Debug.WriteLine("194|Username : " + AppShell.userData.title);
}
else
{
Debug.WriteLine("198|Error");
App.Current.MainPage = new LoginPage();
/*
app.MainPage = new Pages.ErrorPage(
ErroCode.HttpClientRequest,
AppResources.HttpClientRequestError,
"Error text"
);
*/
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Class name : " + ex.ToString());
Debug.WriteLine("Error : " + ex.Message);
/*
app.MainPage = new Pages.ErrorPage(
ErroCode.HttpClientRequest,
AppResources.HttpClientRequestError,
ex.Message
);
*/
}
}
In the MainPage of AppShell:
public MainPage()
{
InitializeComponent();
Debug.WriteLine("DashboardPage");
Debug.WriteLine("End");
}
Debug Input:
Start
193|UserID : 1
194|Username : delectus aut autem
DashboardPage
End
Best Regards,
Alec Liu.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.