Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

swift - 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)
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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...
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...