2

I am trying to get a webpage to appear in my swift application. I have added the WebView and wrote the following code in the controller class but when I run my app, there is only a white screen. Am I missing something?

class WebViewController: UIViewController {


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


    let WebView = UIWebView(frame: view.bounds)

    let url = NSURL(string: "http://www.google.com")
    let request = NSURLRequest(URL:url!)
    WebView.loadRequest(request)
    view.addSubview(WebView)


}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

    }

}
Andrey Chernukha
  • 21,488
  • 17
  • 97
  • 161
Alex Kaczynski
  • 63
  • 1
  • 3
  • 8

3 Answers3

0

Run your code in viewDidLayoutSubviews. You are setting the WebView's frame to the view's bounds. The view's frame has not fully loaded yet.

Pranav Wadhwa
  • 7,666
  • 6
  • 39
  • 61
-1

Never mind, I'm an idiot and forgot the s in http thanks all.

Alex Kaczynski
  • 63
  • 1
  • 3
  • 8
-1

You need to tell the webView who is its delegate, just binding the outlet won't be enough.

In viewDidLoad add this:

self.webView.delegate = self

Then you need to conform to UIWebViewDelegate (which you are already doing, but I suggest you extend your view controller instead):

extension WebViewController: UIWebViewDelegate {
    func webViewDidStartLoad(_ webView: UIWebView) {
        print("Loading")
    }

    func webViewDidFinishLoad(_ webView: UIWebView) {
        print("Finished")
    }
}

And last but not least, you need to allow your application to load external URL's by adding a transport security, I suggest you check this post.

Please note I'm using Swift 3, you may need to make little changes.

Community
  • 1
  • 1
Alonso Urbano
  • 2,266
  • 1
  • 19
  • 26