Francesco
Francesco

Reputation: 169

UIWebView not loading a new url

Everytime I try to load another URL on a UIWebView i get the same error:

SendDelegateMessage(NSInvocation *): delegate (webView:decidePolicyForNavigationAction:request:frame:decisionListener:) failed to return after waiting 10 seconds.

My code about the webView is like:

@IBAction func changeUrl(sender: UIButton) {
    if LEDON {
        let urlStr = NSString(format: "%@/?Led=0", self.url)
        let req = URLRequest(url: URL(string: urlStr as String)!)
        webView.loadRequest(req)
        while(webView.isLoading) {
            sender.isEnabled = false
        }
        sender.isEnabled = true
        LEDON = false;
    } else {
        let urlStr = NSString(format: "%@/?Led=1", self.url)
        let req = URLRequest(url: URL(string: urlStr as String)!)
        webView.loadRequest(req)
        while(webView.isLoading) {
           sender.isEnabled = false
        }
        sender.isEnabled = true
        LEDON = true;
    }
}

If I press the UIButton the first time the code works perfectly, but when I tap it again I get that error. Where am I doing wrong?

"url" variable in the code is a global var and I already check that is correct.

Upvotes: 0

Views: 1289

Answers (2)

Sergey
Sergey

Reputation: 1617

Problem in

while(webView.isLoading) {
    sender.isEnabled = false
}

You have frozen main thread and webView:decidePolicyForNavigationAction:request:frame:decisionListener: can't be invoke.

Try to use this:

func viewDidLoad()
{
    ...
    webView.delegate = self;//UIWebView
    //webView. navigationDelegate = self;//WKWebView
}

@IBAction func changeUrl(sender: UIButton) {
    if LEDON {
        let urlStr = NSString(format: "%@/?Led=0", self.url)
        let req = URLRequest(url: URL(string: urlStr as String)!)
        webView.loadRequest(req)
        sender.isEnabled = false
        LEDON = false;
    } else {
        let urlStr = NSString(format: "%@/?Led=1", self.url)
        let req = URLRequest(url: URL(string: urlStr as String)!)
        webView.loadRequest(req)
        sender.isEnabled = false
        LEDON = true;
    }
}

For UIWebView you need to use

func webViewDidFinishLoad(UIWebView)
{
    yourButton.isEnabled = true
}

For WKWebView

func webView(_ webView: WKWebView, 
            didFinish navigation: WKNavigation!)
{
    yourButton.isEnabled = true
}

======================================

If you want use while loop try to change it for this:

while(webView.isLoading) {
    sender.isEnabled = false
    RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.5))
}

Upvotes: 1

ewan
ewan

Reputation: 276

You need to allow http and https on your app :

In your info.plist :

In Info.plist file add a dictionary with key 'NSAppTransportSecurity'

Add another element inside dictionary with key 'Allow Arbitrary Loads'

enter image description here

Upvotes: 1

Related Questions