Xamarin iOS WKWebView DidFinishNavigation和DidStartProvisionalNavigation未被调用

时间:2016-04-20 20:19:19

标签: xamarin xamarin.ios wkwebview

我正在iOS Xamarin中实现WKWebView,我想在加载启动和加载完成时做一些事情。我已经实现了IWKNavigationDelegate并添加了以下函数,但是没有调用它们。我错过了什么

班级定义

 public partial class MasterViewController : UIViewController,IScanSuccessCallback, IWKScriptMessageHandler, IWKNavigationDelegate
{ }

导航代表功能

    public void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
    {
        Console.WriteLine ("DidFinishNavigation");
    }

    public void DidFailNavigation( WKWebView webView, WKNavigation navigation, NSError error )
    {
        // If navigation fails, this gets called
        Console.WriteLine("DidFailNavigation");
    }
    public void DidFailProvisionalNavigation( WKWebView webView, WKNavigation navigation, NSError error )
    {
        // If navigation fails, this gets called
        Console.WriteLine("DidFailProvisionalNavigation");
    }
    public void DidStartProvisionalNavigation( WKWebView webView, WKNavigation navigation )
    {
        // When navigation starts, this gets called
        Console.WriteLine("DidStartProvisionalNavigation");
    }

2 个答案:

答案 0 :(得分:11)

补充杰森的答案。

您缺少可选委托方法所需的ExportAttribute,每当您IFooInterface成为ObjC委托时,Xamarin Studio自动完成引擎都会为您生成此Foo键入override(它应列出可选成员而非可选成员)。只有可选成员(c#接口中的非抽象成员)才需要ExportAttribute

enter image description here

在这种特殊情况下,WKNavigationDelegate ObjC协议的所有成员都是可选的,因此您需要Export属性和ObjC选择器作为参数。

您需要在使用语句中添加using Foundation,其中包含ExportAttribute

[Export ("webView:didFinishNavigation:")]
public void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
{
    Console.WriteLine ("DidFinishNavigation");
}

[Export ("webView:didFailNavigation:withError:")
public void DidFailNavigation( WKWebView webView, WKNavigation navigation, NSError error )
{
    // If navigation fails, this gets called
    Console.WriteLine("DidFailNavigation");
}

[Export ("webView:didFailProvisionalNavigation:withError:")]
public void DidFailProvisionalNavigation( WKWebView webView, WKNavigation navigation, NSError error )
{
    // If navigation fails, this gets called
    Console.WriteLine("DidFailProvisionalNavigation");
}

[Export ("webView:didStartProvisionalNavigation:")]
public void DidStartProvisionalNavigation( WKWebView webView, WKNavigation navigation )
{
    // When navigation starts, this gets called
    Console.WriteLine("DidStartProvisionalNavigation");
}

希望这有帮助。

答案 1 :(得分:2)

您需要将NavigationDelegate类显式分配给webview

WKWebView web = new WKWebView();

// if the current class implements IWKNavigationDelegate, you can do this
web.NavigationDelegate = this;

// or you can create a separate class that implements IWKNavigationDelegate
web.NavigationDelegate = new MyWebDelegate();