3

Hello when I use WKWebView codes with Swift 3 gives me this error

'URLRequest'; did you mean to use 'as' to explicitly convert?

I think this is bug I need help or ideas ? My codes under below Thanks

import UIKit
import WebKit

class SocialsViewController: UIViewController, WKNavigationDelegate {


    var webView = WKWebView()


    override func viewDidLoad() {
        super.viewDidLoad()

        let url = NSURL(string: "https://facebook.com")!
        webView.loadRequest(NSURLRequest(url: url))
        webView.allowsBackForwardNavigationGestures = true


    }


}
SwiftDeveloper
  • 7,244
  • 14
  • 56
  • 85

2 Answers2

15

Use URL and URLRequest instead:

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

This is quite similar to https://stackoverflow.com/a/37812485/2227743: you either use NSURL and have to downcast it as URL, or you directly use the new Swift 3 structs.

If you follow the error message, your example would become:

let url = NSURL(string: "https://facebook.com")!
webView.load(URLRequest(url: url as URL))

It could be even worse:

let url = NSURL(string: "https://facebook.com")!
webView.load(NSURLRequest(url: url as URL) as URLRequest)

All this works but of course it's much better to start using URL and URLRequest in Swift 3, without using all this downcasting.

Community
  • 1
  • 1
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
-1

Try this one

 let myUrl = URL(string: "https://facebook.com")!
    webView.loadRequest(URLRequest(url:myUrl));
Nirmal Bajpai
  • 229
  • 1
  • 8
  • No. In Swift 3, it's `load`, not `loadRequest`, and I've already answered with a correct solution. – Eric Aya Nov 30 '16 at 13:46
  • Yes! Mr Eric you already provide correct solution. I just change name to differentiate argument "url" and variable of URL struct "myUrl". which is little confusing for freshers. Thanks – Nirmal Bajpai Dec 01 '16 at 08:37