如何在WKWebView加载完成后调用ShowWebViewer方法(C#)
Fix: Call
ShowWebViewer After WKWebView Finishes Loading Hey there! Let's get your ShowWebViewer method to fire only after the WKWebView has finished loading the requested link, instead of immediately.
The Problem with Your Current Code
Your line WebViewer.LoadRequest(url).Invoke(ShowWebViewer) is directly executing ShowWebViewer right away—this doesn't wait for the asynchronous web request to complete. LoadRequest returns a WKNavigation object, but using Invoke here just runs the delegate synchronously, ignoring the actual loading state.
The Solution: Use WKNavigationDelegate
To trigger ShowWebViewer only after the page loads, we need to use WKWebView's navigation delegate to listen for the "finish loading" event. Here's how to implement it:
- Make your class implement the
IWKNavigationDelegateinterface. - Assign the
NavigationDelegateproperty of your WKWebView to your class instance. - Implement the
DidFinishNavigationmethod, where you'll callShowWebViewer.
Full Modified Code Example
public class YourViewController : UIViewController, IWKNavigationDelegate { private WKWebView WebViewer; public void SetLink(string link) { WebViewer = new WKWebView(View.Frame, new WKWebViewConfiguration()); // Assign the navigation delegate to this class instance WebViewer.NavigationDelegate = this; WebViewer.SizeToFit(); var url = NSUrlRequest.FromUrl(NSUrl.FromString(link)); WebViewer.LoadRequest(url); // Remove the Invoke call—we'll trigger ShowWebViewer via the delegate } // This method is called when the web view finishes loading successfully [Export("webView:didFinishNavigation:")] public void DidFinishNavigation(WKWebView webView, WKNavigation navigation) { // Now call ShowWebViewer since loading is complete ShowWebViewer(); } // Optional: Handle failed navigation cases [Export("webView:didFailNavigation:withError:")] public void DidFailNavigation(WKWebView webView, WKNavigation navigation, NSError error) { // Add logic here to handle loading errors (e.g., show an alert to the user) Console.WriteLine($"Web view failed to load: {error.LocalizedDescription}"); } private void ShowWebViewer() { // Your existing ShowWebViewer implementation goes here } }
How This Works
- By setting
WebViewer.NavigationDelegate = this, you're telling the WKWebView to notify your class about navigation events like loading start, finish, or failure. - The
DidFinishNavigationmethod is an exported callback that gets triggered automatically when the web view successfully completes loading the requested page. This is where you safely callShowWebViewer.
内容的提问来源于stack exchange,提问作者Darius Buhai
相关产品推荐
相关产品推荐

