1

started learning swift two weeks ago, with no previous programming experience, and I can't for the life of me figure out why this wouldn't work to check for nil. it just crashes when trying to load a web page if the user enters an invalid URL. This is the ENTIRETY of the code.

import UIKit; import WebKit

class ViewController: UIViewController {

@IBOutlet weak var adressBar: UITextField!
@IBOutlet weak var webView: WKWebView!

override func viewDidLoad() {
    super.viewDidLoad()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

@IBAction func returnPressed(_ sender: Any) {
    if let adressBarText = adressBar.text {
        if let myURL = URL(string: adressBarText) {
            let myRequest = URLRequest(url: myURL)
            webView.load(myRequest)

            adressBar.resignFirstResponder()
            print("EYYYYY")
        } else {
            print("BOOOO")
        }
    }
}

}

Truebro
  • 11
  • 2
  • hey @Truebro, which line has error when crashes ? it has 2 optional checking, did you check it out that is `addressBarText` and `myURL` is right ? – eemrah Mar 03 '18 at 20:53
  • This code can only crash if `webView / adressBar ` is an IBOutlet and not connected in Interface Builder – vadian Mar 03 '18 at 20:55
  • The debugger doesn't give a clear error message at all, just some vague memory reference I think: Thread 1: EXC_BAD_ACCESS (code=1, address=0x10) It doesn't show the usual found NIL when unwrapping error. My outlets are all connected, triple checked that, and it works fine if I enter a valid URL. Put the ENTIRE codebase in the OP. – Truebro Mar 03 '18 at 21:39
  • @Truebro Your code seems fine. It might be an issue in your storyboard file - like connections to actions or outlets that no longer exist. – d.felber Feb 12 '19 at 09:30

1 Answers1

1

Try this method

func verifyUrl (urlString: String?) -> Bool {
    //Check for nil 
    if let urlString = urlString { 
        // create NSURL instance
        if let url = NSURL(string: urlString) {
            // check if your application can open the NSURL instance 
            return UIApplication.sharedApplication().canOpenURL(url)
        }
    }

    return false
}

https://stackoverflow.com/a/30130535/8069241

maxwell
  • 3,788
  • 6
  • 26
  • 40