我正在努力制作一个功能,所以当你按下按钮时,你会打开餐厅的网站并且工作得很好,但有些餐馆没有网站。
var OnlineMenuLinks = ["https://static.wixstatic.com/media/ed1b11_59335d19e484482e8c0dc9ef0caee605~mv2.jpg/v1/fill/w_708,h_992,al_c,q_85/ed1b11_59335d19e484482e8c0dc9ef0caee605~mv2.jpg","","","http://stackoverflow.com/"]
@IBAction func OpenOnline(_ sender: Any) {
let url = URL(string: OnlineLinks[MyIndex])!
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
链接目前正在打开,一切都很好。
虽然我想在数组中有一个空的""
时,UIAlertController会出现并说出例如#34;这家餐厅没有网站。"有可能吗?
感谢您的帮助! :)
答案 0 :(得分:2)
是的可能
func open(_ url: URL?) {
if let url = url {
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:],completionHandler: { (success) in
print("Open Safari \(success)")
})
} else {
let success = UIApplication.shared.openURL(url)
print("Open Safari \(success)")
}
}else{
let alert = UIAlertController(title: "Empty!", message: "This restaurant has no website.", preferredStyle: .alert)
let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
}
}
答案 1 :(得分:2)
var onlineMenuLinks = ["https://static.wixstatic.com/media/ed1b11_59335d19e484482e8c0dc9ef0caee605~mv2.jpg/v1/fill/w_708,h_992,al_c,q_85/ed1b11_59335d19e484482e8c0dc9ef0caee605~mv2.jpg","","","http://stackoverflow.com/"]
let myIndex: Int = 0
func openOnline(_ sender: Any) {
let string = onlineMenuLinks[myIndex]
if string.characters.count > 0, let url = URL(string: string), UIApplication.shared.canOpenURL(url) {
// valid URL
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
} else {
// invalid URL
let alert = UIAlertController(title: "This restaurant has no website.", message: nil, preferredStyle: .alert)
UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true)
}
}
答案 2 :(得分:0)
不检查字符串有效性。在您的情况下,每次URL
无效时都应显示错误(空的String
不会产生有效的URL
实例)。
var OnlineMenuLinks = ["https://static.wixstatic.com/media/ed1b11_59335d19e484482e8c0dc9ef0caee605~mv2.jpg/v1/fill/w_708,h_992,al_c,q_85/ed1b11_59335d19e484482e8c0dc9ef0caee605~mv2.jpg","","","http://stackoverflow.com/"]
@IBAction func OpenOnline(_ sender: Any) {
if let url = URL(string: OnlineLinks[MyIndex]) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
} else {
// show error
}
}
如果MyIndex
超出数组长度,则可能需要检查数组计数。
guard OnlineLinks.count > MyIndex else {
// throw an error
}