Abe
Abe

Reputation: 1929

Xamarin iOS ViewDidAppear is not called when opening app from background

I am new to mobile development. I would like to show a different screen if GPS is not enabled. I have put the code in the view did appear to show the new screen this works most of the time. However when app returns from background the new screen is not shown. After debugging i found that when the app returns to foreground Viewdidload/viewdidappear/the constructor of the controller is not called.

Is there an override which I can use to when the app returns from background on the controller. Also after research I found this link

My Research

If this is the way forward, can someone help me convert this code to Xamarin ios.

Thanks in advance.

Upvotes: 1

Views: 1004

Answers (2)

AZ_
AZ_

Reputation: 21899

You can also use default notification center and then call your ViewModel methods.

NSNotificationCenter.DefaultCenter.AddObserver(UIScene.WillEnterForegroundNotification,
                notification =>
                {
                    ViewModel.ViewAppearing();
                });

Bonus:

If you'll put this code in ViewDidLoad then it will add multiple observers which will cause the observer to trigger multiple times. Save NSNotificationCenter.DefaultCenter.AddObserver return token and then in ViewWillDisappear you can just dispose the token. It will now not called multiple times now.

Upvotes: 0

Junior Jiang
Junior Jiang

Reputation: 12723

In Xamarin IOS , adding Notifications in ViewDidLoad Method , can do that in ViewDidAppear.

public override void ViewDidLoad ()
{
     base.ViewDidLoad ();

     UIApplication.Notifications.ObserveWillEnterForeground ((sender, args) => {
         Console.WriteLine("Welcome back!");
         //Add code from ViewDidAppear method here
     });
}

Here is the IOS LifeCycle document.

Upvotes: 1

Related Questions