How to load URL in UIWebView in Swift?

2020-01-26 04:29发布

I have the following code:

UIWebView.loadRequest(NSURLRequest(URL: NSURL(string: "google.ca")))

I am getting the following error:

'NSURLRequest' is not convertible to UIWebView.

Any idea what the problem is?

标签: swift ios8
18条回答
beautiful°
2楼-- · 2020-01-26 04:56

UIWebView in Swift

@IBOutlet weak var webView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()
        let url = URL (string: "url here")
        let requestObj = URLRequest(url: url!)
        webView.loadRequest(requestObj)
    // Do any additional setup after loading the view.
}

/////////////////////////////////////////////////////////////////////// if you want to use webkit

@IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
    super.viewDidLoad()

    let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.webView.frame.size.height))
    self.view.addSubview(webView)
    let url = URL(string: "your URL")
    webView.load(URLRequest(url: url!))`
查看更多
看我几分像从前
3楼-- · 2020-01-26 04:57

loadRequest: is an instance method, not a class method. You should be attempting to call this method with an instance of UIWebview as the receiver, not the class itself.

webviewInstance.loadRequest(NSURLRequest(URL: NSURL(string: "google.ca")!))

However, as @radex correctly points out below, you can also take advantage of currying to call the function like this:

UIWebView.loadRequest(webviewInstance)(NSURLRequest(URL: NSURL(string: "google.ca")!))   
查看更多
【Aperson】
4楼-- · 2020-01-26 04:59

For swift 4.2, 5+

@IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {
       super.viewDidLoad()
           //Func Gose Here 
          let url = URL(string: link)
          let requestObj = URLRequest(url: url! as URL)
           webView.loadRequest(requestObj)

       }
查看更多
该账号已被封号
5楼-- · 2020-01-26 05:03

For Swift 3.1 and above

let url = NSURL (string: "Your Url")
let requestObj = NSURLRequest(url: url as! URL);
YourWebViewName.loadRequest(requestObj as URLRequest)
查看更多
Luminary・发光体
6楼-- · 2020-01-26 05:04

Swift 3

@IBOutlet weak var webview: UIWebView!
webview.loadRequest(URLRequest(url: URL(string: "https://www.yourvideo.com")!))
查看更多
混吃等死
7楼-- · 2020-01-26 05:05

Swift 3 - Xcode 8.1

 @IBOutlet weak var myWebView: UIWebView!

    override func viewDidLoad() {
            super.viewDidLoad()

            let url = URL (string: "https://ir.linkedin.com/in/razipour1993")
            let requestObj = URLRequest(url: url!)
            myWebView.loadRequest(requestObj)

        }
查看更多
登录 后发表回答