简体   繁体   中英

OnAppearing Method on IOS

When my app is in the background and goes to foreground, the OnAppearing() method doesnt work in IOS or when the phone is locked and then unlocked and the app is in the foreground the method OnAppearing() isnt called, on Android everything works fine. I found this guide below, but still doesnt work, i have the last version of xamarin forms.

Guide: https://kent-boogaart.com/blog/hacking-xamarin.forms-page.appearing-for-ios

Can anyone help me?

As you have seen, the "lifecycles" within iOS are different. One way that helps is to use the Application lifecycles and tie those into Page events (or Commands if needed).

In your Application subclass add a couple of public EventHandlers and tie those into the OnResume (and OnSleep if needed)

public partial class App : Application
{
    public EventHandler OnResumeHandler;
    public EventHandler OnSleepHandler;

    public App()
    {
        InitializeComponent();
        MainPage = new MyPage();
    }

    protected override void OnSleep()
    {
        OnSleepHandler?.Invoke(null, new EventArgs());
    }

    protected override void OnResume()
    {
        OnResumeHandler?.Invoke(null, new EventArgs());
    }
}

Now in your ContentPage subclass, add a handler that tracks when that page comes back from being in the background, kind-of an "OnAppearing after OnPause" handler...

void Handle_OnResumeHandler(object sender, EventArgs e)
{
    Console.WriteLine("OnPauseResumeWithPage");
}

protected override void OnAppearing()
{
    (App.Current as App).OnResumeHandler += Handle_OnResumeHandler;
    base.OnAppearing();
}

protected override void OnDisappearing()
{
    (App.Current as App).OnResumeHandler -= Handle_OnResumeHandler;
    base.OnDisappearing();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM