0

I was wondering how to get all the information from a annotation in swift when tapped on. There is this article: Swift, How to get information from a custom annotation on clicked

But that doesn't answer my question. I made some modifications to the code.

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    if let annotationTitle = view.annotation?.title {
        if let annotationPhone = view.annotation?.phoneNumber as? MKAnnotationView {
            print("User tapped on annotation with title: \(annotationPhone!)")
        }
        print("User tapped on annotation with title: \(annotationTitle!)")
    }
}

Creating the pin if this helps at all:

let annotation = MKPointAnnotation()
annotation.coordinate = item.placemark.coordinate
annotation.title = item.name
annotation.subtitle = "Coffee Shop"
self.map.addAnnotation(annotation)

But I get the error:

Value of type 'MKAnnotation' has no member 'phoneNumber'

What am I doing wrong?

CodeShady
  • 46
  • 11
  • `as? MKAnnotationView`. Did you used a custom `MKAnnotationView` or custom `MKAnnotation` with a property `phoneNumber`? if yes, use this one: `if let annotationView as ? MyCustomAnnotationView, let annotationPhone = view.annotation.phoneNumber {`, or whatever is the path you used (for the example, I assumed it was `MKAnnotationView`). – Larme Jul 03 '18 at 19:09
  • I am using MKPointAnnotation – CodeShady Jul 03 '18 at 19:10

1 Answers1

0

Just subclass MKPointAnnotation with property called phoneNumber :

class PhoneAnnotation : MKPointAnnotation {
    var phoneNumber: String?
}

After this you can get the phoneNumber value (and other custom values) from annotation like this:

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    if let phoneNumber = (view.annotation as? PhoneAnnotation)?.phoneNumber {

    }
}