我試圖加載一個網頁,當一個註釋的標註被點擊,所以我試圖用switch語句來檢查註釋標題,然後顯示正確的網頁。然而,作爲一個快速的初學者,選擇權給了我相當多的麻煩。我已經嘗試了幾個變化,但不斷收到錯誤。這裏是我的代碼:嘗試使用URL字符串時遇到swift optionals
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
let restaurant = view.annotation as! Restaurants
let placeName = restaurant.title!
let placeInfo = restaurant.info
switch placeName {
case "Chili's":
if let urlString = "http://www.chilis.com" as? String {
let chilisUrl = URL(string: urlString)
self.webView.load(URLRequest(url: chilisUrl!))
}
case "George's":
if let urlString = "http://www.georges-ny.com" as? String {
let georgesUrl = URL(string: urlString)
self.webView.load(URLRequest(url: georgesUrl!))
}
case "TGI Friday's":
if let urlString = "https://www.tgifridays.com" as? String {
let fridaysUrl = URL(string: urlString)
self.webView.load(URLRequest(url: fridaysUrl!))
}
case "Reserve Cut":
if let urlString = "http://reservecut.com" as? String {
let rcUrl = URL(string: urlString)
self.webView.load(URLRequest(url: rcUrl!))
}
case "Bill's Bar & Burger":
if let urlString = "http://www.billsbarandburger.com" as? String {
let billsUrl = URL(string: urlString)
self.webView.load(URLRequest(url: billsUrl!))
}
default:
if let urlString = "http://www.oharaspubnyc.com" as? String {
let oharasUrl = URL(string: urlString)
self.webView.load(URLRequest(url: oharasUrl!))
}
}
webView.allowsBackForwardNavigationGestures = true
self.view = webView
}
我剛剛使用URL直接像self.webView.load(URLRequest(url: "http://reservecut.com" as! URL))
和
let rcUrl = URL(string: "http://reservecut.com")
self.webView.load(URLRequest(url: rcUrl!))
但那些給了我的問題,以及嘗試。
如何安全地解開(?)並在此處使用URL字符串?我想這也值得問一問,是否有更清潔/更有效的方法來解決這個問題?我想過使用一本字典,但從長遠來看,它最終會成爲更多的代碼。無論如何,感謝您的任何建議!
對於初學者來說,爲什麼你鑄造一個字符串轉換爲字符串? '如果讓urlString =「http://www.chilis.com」爲? String'它總是會成功... – Alexander
請在發佈有關錯誤的問題時,重要的是您的問題包括完整的錯誤信息以及明確指出導致錯誤的行。 – rmaddy
'「www.http://georges-ny.com」'?真?? – matt