Running Startup Tasks In Xamarin Forms
Mobile apps are commonly required to run startup tasks such as making a call to an API or validating tokens for authentication all before showing the first screen to the user. This is the requirement I got last week and I wanted to take the time here to share my solution.
iOS and Android require a startup screen. If that screen is not available yet because of some startup tasks that are running iOS will through the following error
Objective-C exception thrown. Name: NSInternalInconsistencyException Reason: Application windows are expected to have a root view controller at the end of application launch Native stack trace: 0 CoreFoundation
This means that there was no screen ready at the time iOS finished its Startup tasks. To avoid this Xamarin developers know to load their main startup screen or page in the App.xaml file Constructor. However, potentially long running tasks or API calls should not be placed here.
To solve this problem we have the Async method protected override async void OnStart() method.
The beauty of this method is that it can be run using Async and Await and can be used for long running tasks. So if you have a Loading screen you can show that in the App.xaml Constructor and then show your Apps first screen in the OnStart method after you have finished your startup tasks. Here is my code. I use Prism for Navigation.
I’m doing a lot of stuff here but I think you get the idea. Your first page will only show when all the these startup tasks are complete.
I hope this helps!