Как определить, когда приложение перемещается на задний план или на передний план в классе UIViewController xamarin.ios

#c# #xamarin.ios

#c# #xamarin.ios

Вопрос:

Мне нужно включать и отключать некоторые таймеры, когда приложение перемещается на задний или передний план, который находится в UIViewController. Но, похоже, я могу получить доступ только к didEnterBackground и WillEnterForeground только в классе AppDelegate. Есть ли какой-либо способ обнаружить эти два события из класса UIViewController?

Комментарии:

1. docs.microsoft.com/en-us/xamarin/ios/app-fundamentals/…

2. в документах ничего не указано о доступе к событиям из uiviewcontroller

Ответ №1:

Вы не можете получить доступ к этим событиям на уровне uiviewcontroller, вы можете получить их только на уровне приложения.

В AppDelegate вы можете отправлять уведомления при использовании DidEnterBackground или WillEnterForeground :

 public class AppDelegate : UIResponder, IUIApplicationDelegate {

    [Export("window")]
    public UIWindow Window { get; set; }

    [Export ("application:didFinishLaunchingWithOptions:")]
    public bool FinishedLaunching (UIApplication application, NSDictionary launchOptions)
    {
        // Override point for customization after application launch.
        // If not required for your application you can safely delete this method
        return true;
    }

    [Export("applicationDidEnterBackground:")]
    public virtual void DidEnterBackground(UIKit.UIApplication application) {

        NSNotificationCenter.DefaultCenter.PostNotificationName("DidEnterBackground",this);
    }

    [Export("applicationWillEnterForeground:")]
    public virtual void WillEnterForeground(UIKit.UIApplication application) {

        NSNotificationCenter.DefaultCenter.PostNotificationName("WillEnterForeground", this);
    }      
}
 

Затем в UIViewController, который вы хотите знать, добавьте сервер:

 public partial class ViewController : UIViewController
{
    public ViewController (IntPtr handle) : base (handle)
    {
    }

    public override void ViewDidLoad ()
    {
        base.ViewDidLoad ();
        // Perform any additional setup after loading the view, typically from a nib.

        NSString backgroundStr = new NSString("DidEnterBackground");
        NSString foregroundStr = new NSString("WillEnterForeground");

        NSNotificationCenter.DefaultCenter.AddObserver(backgroundStr, enterBackgroundMethod);
        NSNotificationCenter.DefaultCenter.AddObserver(foregroundStr, enterForegroundMethod);

    }

    public void enterBackgroundMethod(NSNotification notification)
    {
        Console.WriteLine("enterBackgroundMethod");
    }

    public void enterForegroundMethod(NSNotification notification)
    {
        Console.WriteLine("enterForegroundMethod");
    }
}