-1

I'm trying to add subview to mainView but sometime is working sometime got error. I don't know why like that.

What's wrong ? Thank.

func setURL(url_string : String){
    DispatchQueue.main.async {
        self.webView = WKWebView(frame : CGRect(x: 0.0, y: 0.0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))

        if let url = URL(string: url_string) {
            self.webView?.navigationDelegate = self
            if let web = self.webView {
                self.mainView.addSubview(web) // got Error Here
            }
            self.webView?.load(URLRequest(url: url))
        }
    }
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    self.loadingIndicator.stopAnimating()
    self.loadingIndicator.isHidden = true
}
  • means your mainView is nil or web is nil? – Ashish Kakkad Jun 13 '18 at 12:45
  • `web` couldn't , because it's implicitly unwrapped via optional bindings, so... – thxou Jun 13 '18 at 12:48
  • we need information about the point where you set the `self.mainView` object. – thxou Jun 13 '18 at 12:51
  • Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Tamás Sengel Jun 13 '18 at 13:35
  • Without seeing more, I would venture to say that your `mainView` is the culprit. Find its declaration and check it – Jake Jun 13 '18 at 13:40
  • You should show how you are creating `mainView`. Meanwhile you can fix crash by doing `self.mainView?.addSubview(web)` – Kamran Jun 13 '18 at 13:44

1 Answers1

0

I'm try to fixed with add subview in function didFinish is work. Thank //mainView is just UIView //@IBOutlet weak var mainView: UIView!

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    if let web = self.webView { 
        self.mainView.addSubview(web)
    }
    self.loadingIndicator.stopAnimating()
    self.loadingIndicator.isHidden = true
}