Swift集成UIWebView遇报错:'init(URL:)'已重命名为'init(url:)'求解决
Hey there! Let's get this sorted out quickly. That error pops up because Swift updated its naming conventions for initializers, and the older tutorial you're referencing uses the outdated capitalized parameter name. Here's how to fix it:
1. Update the Initializer Syntax
Chances are your code looks something like this (from the old tutorial):
let request = URLRequest(url: URL(URL: yourURL))
Simply change the capitalized URL parameter to lowercase url:
let request = URLRequest(url: URL(url: yourURL))
Even better, if you're starting with a string URL, use the more common URL(string:) initializer (with proper validation to avoid crashes):
guard let targetURL = URL(string: "https://your-target-url.com") else { print("Oops, invalid URL!") return } let request = URLRequest(url: targetURL)
2. A Critical Heads-Up: UIWebView is Deprecated
While fixing the syntax will get your code running, I should mention that UIWebView was deprecated by Apple in iOS 12. It's slow, lacks support for modern web features, and has security vulnerabilities. For a better experience (and to avoid future issues), switch to WKWebView instead—it's Apple's recommended replacement.
Here's a quick example of setting up WKWebView:
import WebKit class YourViewController: UIViewController, WKNavigationDelegate { private var webView: WKWebView! override func viewDidLoad() { super.viewDidLoad() // Initialize WKWebView and add it to your view webView = WKWebView(frame: view.bounds) webView.navigationDelegate = self view.addSubview(webView) // Load your desired URL guard let url = URL(string: "https://your-target-url.com") else { return } webView.load(URLRequest(url: url)) } }
This will give you better performance, more features, and keep your app compliant with Apple's latest guidelines.
内容的提问来源于stack exchange,提问作者neda Derakhshesh

