iOS WKWebView部分网页链接无法加载,求解决方案
Hey there, let's break down why this is happening and how to fix it quickly!
The Root Cause
Unlike Safari or Chrome, which automatically infer and add the HTTP/HTTPS protocol prefix when you enter a link like www.google.com or apple.com, WKWebView is strict about URL formatting. It requires a fully qualified URL with an explicit protocol (http:// or https://) to load content properly. Without that prefix, WKWebView doesn't know how to resolve the address, hence the failed loads.
Step-by-Step Solution
You'll need to add a quick check before loading any URL in your WKWebView to ensure the protocol is present. Here's how to implement this, even in your viewDidLoad method:
Create a helper function to normalize URLs
func normalizeURL(_ urlString: String) -> URL? { var formattedString = urlString.trimmingCharacters(in: .whitespacesAndNewlines) // Check if the string already has a protocol if !formattedString.hasPrefix("http://") && !formattedString.hasPrefix("https://") { // Add https:// as default (you can switch to http:// if needed) formattedString = "https://\(formattedString)" } return URL(string: formattedString) }Use this helper when loading URLs in WKWebView
Modify yourviewDidLoadcode to leverage the helper function before initiating the web request:override func viewDidLoad() { super.viewDidLoad() let webView = WKWebView(frame: view.bounds) view.addSubview(webView) // Example link without prefix (replace with your target link) let targetLink = "www.example.com" if let validURL = normalizeURL(targetLink) { let webRequest = URLRequest(url: validURL) webView.load(webRequest) } else { // Handle invalid URL scenario print("Unable to parse the provided link into a valid URL") } }
Additional Notes
- If you're handling user-input URLs, you can add extra robustness checks (like fixing cases where users type
http:instead ofhttp://) to cover edge scenarios. - Your existing working links (with explicit http/https prefixes) will continue to work seamlessly with this helper, as it skips protocol addition when one already exists.
内容的提问来源于stack exchange,提问作者MikeIOSMike

