0

My first app with swift... failing terribly.

I'm trying to open a website using webview and found this code online.

class ViewController: UIViewController {
@IBOutlet var webView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()
    let url = NSURL(string: "http://www.sourcefreeze.com")
    let request = NSURLRequest(URL: url!)
    webView.loadRequest(request)
}

Well I get a fatal error: unexpectedly found nil while unwrapping an Optional value

Why should this value be null ?!

Mr. Toast
  • 941
  • 3
  • 11
  • 27

2 Answers2

1

One of two things may be going on.

  1. Your webView is not hooked up to a storyboard element.
  2. Your URL object isn't be initialized

I think it's the former, but I've taken the liberty of making your code safer by optionally binding your NSURL object.

class ViewController: UIViewController {

    @IBOutlet var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        if let url = NSURL(string: "http://www.sourcefreeze.com") {
            let request = NSURLRequest(URL: url)
            webView.loadRequest(request)
        }
}
ArtSabintsev
  • 5,170
  • 10
  • 41
  • 71
0

Change webView.loadRequest(request) to webView?.loadRequest(request).

You need to unblock Transport Security which doesn't allow http loads. Try this.

Community
  • 1
  • 1
Mtoklitz113
  • 3,828
  • 3
  • 21
  • 40
  • Check the updated answer. And as the other answer says, I don't think you've hooked up the @IBOutlet property in your storyboard. – Mtoklitz113 Jun 16 '16 at 16:58