当我的应用无法打开网址时,我想通过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)
}
应该在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
}
也许是因为你忘记在.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)
}))
}