Search code examples
swiftuikit

Alert saying it's blocked when I try to open a URL that isn't allowed


I actually tried to add if-else statement in the showPage func, but it doesn't work correctly.

func openPage(action : UIAlertAction){
    if  let url = URL(string: "http://" + action.title!) {
        webView.load(URLRequest(url: url))
    }else{
        let ac = UIAlertController(title: "Valid URL", message: "wrong url", preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "Close", style: .cancel))
        present(ac , animated: true)
    }
}

Solution

  • There are some syntax errors in your code.

    1. It's not possible to declare a variable in the " if " statement.
    let url = URL(string: "http://" + action.title!);
    
    if (URL) {
        //do something...
    }
    
    1. Class constructor URL cannot be invoked without 'new'.
    let url = new URL(string: "http://" + action.title!);
    
    1. It's better to put all of your codes in a try-catch block.
    function openPage(action: UIAlertAction) {
        try {
            //do something...
        } catch (e) {
            //handle error...
        }
    }