Eduard
Eduard

Reputation: 536

Setting a delegate makes app crash

I instantiate a WebViewController to present it modally (UIViewController with a webView in it) and trying to set current class as a delegate for its webView, but it causes app to crash.

let webVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "WebViewController") as! WebViewController
                        UIApplication.topViewController()?.present(webVC, animated: true, completion: {
                            webVC.webView.load(data, mimeType: response.mimeType!, textEncodingName: response.textEncodingName!, baseURL: response.url!)
                            webVC.webView.delegate = self
                        })

I tried to remove "vc.webView.delegate = self" part, and page loads just fine. Any thoughts what can cause a problem here?

enter image description here

Upvotes: 0

Views: 784

Answers (2)

Castle - Builder
Castle - Builder

Reputation: 31

after addSubView, the view of webVC was retained and the webVC was released (as it is a local variable) you should declare webVC as a global variable, by this way webVC will not be released

Upvotes: 0

Phillip Mills
Phillip Mills

Reputation: 31016

The crash is saying that when the UIWebView tries to send a message to the delegate, the delegate doesn't exist any more. That's the normal cause of objc_msgSend. (Or that you've called a method that doesn't exist...but that's unlikely for an optional method.)

Make sure that you remove the delegate before self goes out of scope or keep the delegate object around if you need it to handle redirects.

Upvotes: 1

Related Questions