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

问题描述 投票:1回答:2

当我的应用无法打开网址时,我想通过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)
}
ios swift uialertcontroller guard
2个回答
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
}

0
投票

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

let 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)
            }))
        }
© www.soinside.com 2019 - 2024. All rights reserved.