我对swift编程还不熟悉,我正在尝试构建一个在地图上显示某个pin的应用程序。当用户单击管脚时,有一个带按钮的注释。如果单击该按钮,它将在Safari中打开一个url。
根据一些教程,我设法有一个功能性的应用程序与引脚和按钮,但我不能设法打开网址。
这是我用来构建应用程序的代码:

struct WebCam {
  var name: String
  var latitude: CLLocationDegrees
  var longitude: CLLocationDegrees
  var url: String
}

class FirstViewController: UIViewController, CLLocationManagerDelegate {

@IBOutlet weak var mapView: MKMapView!

let webcams = [WebCam(name: "WH1", latitude: 51.5549, longitude: -0.108436, url: "www.test.it"),
                WebCam(name: "WH2", latitude: 51.4816, longitude: -0.191034, url: "www.google.it")]

func fetchWebcamsOnMap(_ webcams: [WebCam]) {
  for webcam in webcams {
    let annotations = MKPointAnnotation()
    annotations.title = webcam.name
    annotations.coordinate = CLLocationCoordinate2D(latitude: webcam.latitude, longitude: webcam.longitude)
    mapView.addAnnotation(annotations)
  }
}

extension FirstViewController: MKMapViewDelegate {

func mapView(_ mapView: MKMapView, viewFor annotations: MKAnnotation) ->
MKAnnotationView? {
let identifier = "WebCam"
var view: MKMarkerAnnotationView
// 4
if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
  as? MKMarkerAnnotationView {
  dequeuedView.annotation = annotations
  view = dequeuedView
} else {
  // 5
  view = MKMarkerAnnotationView(annotation: annotations, reuseIdentifier: identifier)
  view.canShowCallout = true
  view.calloutOffset = CGPoint(x: -5, y: 5)
    let mapsButton = UIButton(frame: CGRect(origin: CGPoint.zero,
       size: CGSize(width: 30, height: 30)))
    mapsButton.setBackgroundImage(UIImage(named: "webcam"), for: UIControl.State())
    view.rightCalloutAccessoryView = mapsButton
}

return view

}

这是检索ui按钮的代码
    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
       if control == view.rightCalloutAccessoryView {

       }
   }

我试图通过访问选定的网络摄像头的URL来进行简单的控制台打印
let web = view.annotation as! WebCam
let webURL = WebCam.url

但它显示出一个错误。

最佳答案

WebCam必须是MKPointAnnotation的子类

class WebCam : MKPointAnnotation {
    var url : String

    init(name : String, latitude : CLLocationDegrees, longitude : CLLocationDegrees, url : String) {
        self.url = url
        super.init()
        self.title = name
        self.coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    }
}

然后可以创建实例
let webcams = [WebCam(name: "WH1", latitude: 51.5549, longitude: -0.108436, url: "www.test.it"),
               WebCam(name: "WH2", latitude: 51.4816, longitude: -0.191034, url: "www.google.it")]

fetchWebcamsOnMap可以减少到
func fetchWebcamsOnMap(_ webcams: [WebCam]) {
    mapView.addAnnotations(webcams)
}


let web = view.annotation as! WebCam
let webURL = web.url

会有用的。

10-08 07:20