How to load URL in UIWebView in Swift?

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?


Solution 1:

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")!))   

Swift 5

webviewInstance.load(NSURLRequest(url: NSURL(string: "google.ca")! as URL) as URLRequest)

Solution 2:

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!))`

Solution 3:

Try this:

  1. Add UIWebView to View.

  2. Connect UIWebview outlet using assistant editor and name your "webview".

  3. UIWebView Load URL.

    @IBOutlet weak var webView: UIWebView!
    
    override func viewDidLoad() {
       super.viewDidLoad()
        // Your webView code goes here
       let url = URL(string: "https://www.example.com")
       let requestObj = URLRequest(url: url! as URL)
       webView.load(requestObj)
    }
    

And run the app!!