Xamarin.iOS AddObserver not firing for change event for udpate to UIView.Window

Viewed 32

I'm trying to implement a lifecycle effect in Xamarin.Forms, but am having trouble for the iOS version. For some reason, I can't seem to observe the window changing notification event. Below is my code:

public class CustomLifeCycleEffectRouter : PlatformEffect
{
    private const NSKeyValueObservingOptions ObservingOptions = NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New;

    UIView? _nativeView;
    CustomLifeCycleEffect? _lifeCycleEffect;
    IDisposable _isLoadedObserverDisposable;

    protected override void OnAttached()
    {
        _lifeCycleEffect = Element.Effects.OfType<CustomLifeCycleEffect>().FirstOrDefault() ?? throw new ArgumentNullException($"The effect {nameof(CustomLifeCycleEffect)} can't be null.");

        _nativeView = Control ?? Container;

        _isLoadedObserverDisposable = _nativeView?.AddObserver("window", ObservingOptions, isWindowAttachedObserver);
    }

    protected override void OnDetached()
    {
        _lifeCycleEffect?.RaiseUnloadedEvent(Element);
        _isLoadedObserverDisposable.Dispose();
    }
    
    private void isWindowAttachedObserver(NSObservedChange nsObservedChange)
    {
        if (_nativeView.Window != null)
            _lifeCycleEffect?.RaiseLoadedEvent(Element);
        else
            _lifeCycleEffect?.RaiseUnloadedEvent(Element);
    }
}

I am well aware that the Xamarin.Community Toolkit has a similar effect, but it fires the event to early; I need it to fire when I can navigate up the hiearchy to the root parent. Can anybody see a problem?

0 Answers
Related