1

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Abe
  • 1,879
  • 2
  • 24
  • 39
  • 1
    Natively you'd listen for `UIApplication.willEnterForegroundNotification`. Not sure how it works in Xamarin. – Guy Kogus Jun 18 '19 at 12:09
  • @GuyKogus 's solution will work for you.. – FreakyAli Jun 18 '19 at 12:13
  • Thank you. But I am not sure how to do it in xamarin. Will be good to have some code example. – Abe Jun 18 '19 at 12:15
  • Trying to use the following link https://stackoverflow.com/questions/5967232/how-do-you-register-for-uiapplicationwillenterforegroundnotification-in-monotouc – Abe Jun 18 '19 at 12:26
  • Possible duplicate of [How do you register for UIApplicationWillEnterForegroundNotification in MonoTouch](https://stackoverflow.com/questions/5967232/how-do-you-register-for-uiapplicationwillenterforegroundnotification-in-monotouc) – Cheesebaron Jun 18 '19 at 13:46

2 Answers2

1

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.

Junior Jiang
  • 12,430
  • 1
  • 10
  • 30
0

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.

AZ_
  • 21,688
  • 25
  • 143
  • 191