I have created a Xamarin Forms 5.0 application (VS 2022). My project is composed of the primary application and ports for Android and iOS. I want to add a splash screen that does the following:
- Shows a logo
- In the background, create tables (if they don't already exist)
- Pull data from an external API and load the tables.
- After steps 2 and 3 are completed, close the splash screen and open the main application (.e. dont let the user use the application until steps 2 and 3 complete.)
I wrote the code that does steps 2 and 3 but it runs in the first view that is shown. I would rather run this code in a splash screen. Is there any way to build the splash screen in the primary app without having to add it to each device specific application (i.e. the Android and iOS apps)?
Right now, I run this code in App.xaml.cs OnStart method. But, this causes the screen to just stay blank until the code finishes running, and then the screen displays. This is how I have it setup:
App.xaml.cs
public partial class App : Application
{
static Database database;
public IMyDataStore<MyViewPagesModel> _MyDataStore=> DependencyService.Get<IMyDataStore<MyViewPagesModel>>();
public static Database Database
{
get
{
if (database == null)
{
database = new Database(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "my_db.db3"));
}
return database;
}
}
public App()
{
InitializeComponent();
DependencyService.Register<MyDataStore>();
MainPage = new AppShell();
}
protected override void OnStart()
{
if(Database != null)
{
Database.CreateTables();
Task.Run(async () => await MyDataStore.PullDataFromAPI()).Wait();
}
}
}
MyDataStore.cs
public class MyDataStore: IMyDataStore<MyViewPagesModel>
{
static HttpClient client = new HttpClient();
readonly MyViewPagesModel _pages;
Database db;
private HttpClient httpClient;
public MyDataStore()
{
_pages = new MyViewPagesModel_pages();
db = App.Database;
httpClient = new HttpClient();
}
public async Task PullDataFromAPI(){
//do stuff
}
}
I am trying to run, at startup, both the
Database.CreateTables();
Task.Run(async () => await MyDataStore.PullDataFromAPI()).Wait();
But, I don't want the screen to freeze. I'd like it to display a logo and scroll some loading text, but not sure how? Can this be done in a splash screen or do I need to run these two methods on a different thread?
thanks