You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何判断UIWebView已完成加载并执行代码?

解决UIWebView加载完成后执行代码的问题

Hey there! I’ve run into this exact UIWebView issue before—let’s get it sorted for you. The core fix here is using the UIWebViewDelegate correctly, which is probably where your earlier attempts went off track.

Step 1: Set Up the Delegate

First, make sure your view controller conforms to the UIWebViewDelegate protocol, and assign your web view’s delegate to self. This is non-negotiable—without this, the completion callback won’t ever trigger.

Step 2: Implement the Load Completion Method

The webViewDidFinishLoad(_:) delegate method fires automatically when the web page finishes loading successfully. This is where you’ll drop your post-load code.

Full Working Code Example

Here’s a complete, safe snippet you can adapt to your project:

import UIKit

class YourViewController: UIViewController, UIWebViewDelegate {
    // Ensure you've connected your UIWebView to this IBOutlet in Storyboard/XIB
    @IBOutlet weak var webPage: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Critical: Link the web view to its delegate
        webPage.delegate = self
        
        // Load your page with safe optional binding (no force unwrapping!)
        if let url = URL(string: "https://example.com") {
            let loadRequest = URLRequest(url: url)
            webPage.loadRequest(loadRequest)
        }
    }

    // Triggered when the web page finishes loading
    func webViewDidFinishLoad(_ webView: UIWebView) {
        // 🚀 Add your post-load code here!
        print("Web page fully loaded and ready!")
        
        // Example: Run JavaScript to fetch the page title
        if let pageTitle = webView.stringByEvaluatingJavaScript(from: "document.title") {
            print("Current Page Title: \(pageTitle)")
        }
        
        // You can also update UI, send analytics events, or run other app logic here
    }

    // Optional: Handle load failures to avoid confusion
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        print("Page load failed: \(error.localizedDescription)")
    }
}

Why Your Earlier Attempts Might Have Stopped Loading

If the page froze mid-load before, it’s almost certainly one of these issues:

  • You forgot to set webPage.delegate = self—without this, the web view can’t communicate load status updates, leading to unexpected behavior.
  • You accidentally called webView.stopLoading() somewhere in your code, which abruptly halts the load process.
  • Your delegate method had bugs that crashed the app or blocked the main thread (like long-running synchronous tasks).

Quick Heads-Up: UIWebView is Deprecated

Just a friendly note: Apple deprecated UIWebView back in iOS 12, so for long-term app stability, you should consider migrating to WKWebView (it’s faster, more secure, and has better JavaScript integration). But if you’re stuck with UIWebView for now, the solution above will work perfectly.

内容的提问来源于stack exchange,提问作者Bob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:20:52