“NSURL” is not implicitly convertible to “URL”; did you mean to use “as” to explicitly convert?

女生的网名这么多〃 提交于 2020-01-12 06:42:07

问题


I have latest xcode beta, just trying to load a webpage inside an app.

import UIKit

class ViewController: UIViewController {

    @IBOutlet var webView: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let url = NSURL (string: "https://www.google.com");
        let requestObj = NSURLRequest(URL: url!);
        webView.loadRequest(requestObj);
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

On this line: let requestObj = NSURLRequest(URL: url!); I get following error:

"NSURL" is not implicitly convertible to "URL"; did you mean to use "as" to explicitly convert?

I removed the exclamation mark and I get this error:

Cannot convert value of type "NSURL?" to expected argument type "URL"

I've been trying variations on this code from all over the internet for the past four hours. I'm thinking latest swift just doesn't allow this anymore or something, because nothing works. I'm set to a 10.0 Deployment Target and a Xcode 8.0 compatible. But I've also tried earlier versions for both of those settings and I get the same error across all versions of both.

Yes, my webView on the storyboard is properly connected to the ViewController.swift.


回答1:


In swift 3 you need to use URL instead of NSURL, so create url object like this.

if let url = URL(string: "https://www.google.com") {
    webView.load(URLRequest(url: url))
}



回答2:


Update for Swift 3.1:

    let url = URL(string: "https://www.google.com")
    let request = URLRequest(url: url!)
    webView.load(request)

Notice the use of URL instead of NSURL and load instead of loadRequest.



来源:https://stackoverflow.com/questions/38931870/nsurl-is-not-implicitly-convertible-to-url-did-you-mean-to-use-as-to-expl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!