如果无法打开URL,则显示警报

时间:2019-04-22 14:09:21

标签: ios swift uialertcontroller guard

我想在我的应用无法打开URL时通过UIAlertController向用户显示警报。这是我的代码:

guard let url = URL(string: urlLink) else {
  return
}
UIApplication.shared.open(url, options: [:])

我创建的警报:

let alert = UIAlertController(title: "Warning", message: "Problem with URL.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true)

如果我将警报移动到guard语句中,则永远不会发生。我通过将urlLink更改为某个随机String(例如"123")来进行测试。关于如何显示警报的任何想法?

编辑:

我使用了canOpenURL,它返回了Bool。现在我的代码是:

guard let url = URL(string: urlLink) else {
    return
}
if UIApplication.shared.canOpenURL(url) {
    UIApplication.shared.open(url, options: [:])           
} else {
    let alert = UIAlertController(title: "Warning", message: "Problem with URL.", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
    self.present(alert, animated: true)
}

2 个答案:

答案 0 :(得分:3)

应该在return

之前
guard let url = URL(string: urlLink) , UIApplication.shared.canOpenURL(url) else {

  let alert = UIAlertController(title: "Warning", message: "Problem with URL.",   preferredStyle: .alert)
  alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
  self.present(alert, animated: true)
  return
}

答案 1 :(得分:0)

也许是因为您忘记了在.open方法之后放置完成处理程序,并且还在canOpenURL中添加“作为URL”。 试试这个:

让url = URL(string:urlLink)

        if UIApplication.shared.canOpenURL(url! as URL){

            UIApplication.shared.open(url!, options: [:], completionHandler: nil)
        }
        else{

            let appFailed =  UIAlertController(title: "Warning!", message: "Problem with URL.", preferredStyle: .alert)
            appFailed.addAction(UIAlertAction(title: "Ok", style: .default, handler: {(action) in

                self.present(appFailed, animated: true, completion: nil)
            }))
        }