Search code examples
iosxamarindisposekey-value-observingwkwebview

Where/how to manually dispose observer of WKWebView estimatedProgress


I have been trying to track the estimated loading progress on a WKWebView using KVO on the "estimatedProgress" property in a Xamarin ios UIViewController.

I add an observer like this:

public override void ViewDidLoad()
{
    base.ViewDidLoad();
    ...
    WkView.AddObserver("estimatedProgress", NSKeyValueObservingOptions.New, ProgressObserver);
    ...
}

ProgressObserver looks like this:

public void ProgressObserver(NSObservedChange nsObservedChange)
{
    Console.WriteLine("Progress {0}", WkView.EstimatedProgress);
}

When I run this it returns something like this:

2015-11-17 09:29:15.345 testappiOS[10056:1381155] Progress 0.1
2015-11-17 09:29:15.636 testappiOS[10056:1381155] Progress 0.285892975242258
2015-11-17 09:29:15.949 testappiOS[10056:1381169] Warning: observer object was not disposed manually with Dispose()

Googling " Warning: observer object was not disposed manually with Dispose()" returns information about the need to manually dispose the observer, obviously. But I have not been able to figure out how to apply this to my problem.

Can anyone offer some insight on this?


Solution

  • First you will need to create a private variable to hold the disposable observer:

    private IDisposable progressObserver;
    

    Then assign it from the AddObserver return value but place this to ViewWillAppear method instead:

    this.progressObserver = webView.AddObserver(
        "estimatedProgress", 
        NSKeyValueObservingOptions.New, 
        ProgressObserver);
    

    Dispose it in ViewWillDisappear:

    this.progressObserver.Dispose();